0

I am trying to develop an android app but I don't really have much experience with it. At the moment the App reads all the information from my database like portid,names and fullname etc. Everything is working fine on the virtual devices from Android 4.1 to Android 2.2. I am working with eclipse. But now I wanted to test it on real devices. First I installed it on a Smartphone with Android 4.0. I managed to install the App and to start it. The App also wrote the file but it was empty. Afterwards I installed it on a smartphone with Android 2.3. It also started but I was not able to find the file.

As I've never worked with Android Apps before, can anybody give me some idea how I can figure out why the App is running on ALL the virtual devices but not on the real ones?

Thanks in advance!

my code :

MainActivity.java

    public class MainActivity extends Activity  {

          EditText portid;
          Button lgn;
          String portId, name, fullname, relativename;
          private static String url_login = "http://10.0.2.2/CramerA/login.php";
          private static final String TAG_SUCCESS = "success";
          private static final String TAG_REPLY = "reply";
          public static final String TAG_ID = "id";
          public static final String TAG_NAME = "name";
          public static final String TAG_FULLNAME="fullname";
          public static final String TAG_RELATIVENAME="relativename";
          JSONParser jsonParser = new JSONParser();
         @Override
         protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

        //        StrictMode.ThreadPolicy policy = new    StrictMode.ThreadPolicy.Builder().permitAll().build();
       //       StrictMode.setThreadPolicy(policy);

          portid = (EditText) findViewById(R.id.editText1);
          lgn = (Button) findViewById(R.id.button1);

          lgn.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                // TODO Auto-generated method stub
                portId=portid.getText().toString().trim();
                if(portId.equals("")){
                    Toast.makeText(getApplicationContext(), "Invalid Input!",
                               Toast.LENGTH_SHORT).show();

                    portid.setText("");
                }else{
                    try{
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("portid", portId));
                    JSONObject json = jsonParser.makeHttpRequest(url_login,"GET", params);                          
                    Log.d("Create Response", json.toString());
                    int success = json.getInt(TAG_SUCCESS);
                    if(success == 1)
                    {
                        JSONArray arrayobj = json.getJSONArray("reply");
                        for(int i=0; i< arrayobj.length(); i++)
                        {
                            JSONObject obj = arrayobj.getJSONObject(i);                             
                             portId = obj.getString("portid");
                            name = obj.getString("name");
                            fullname = obj.getString("fullname");
                            relativename=obj.getString("relativename");

                            Toast.makeText(getApplicationContext(), "Successfull",Toast.LENGTH_LONG).show();    

                            StringBuffer buffer=new StringBuffer();
                            buffer.append("Port ID :"+obj.getString("portid")+"\n");
                            buffer.append("Name :"+obj.getString("name")+"\n");
                            buffer.append("Full Name :"+obj.getString("fullname")+"\n");
                            buffer.append("Relative Name :"+obj.getString("relativename")+"\n");

                            showMessage("Port Details", buffer.toString());

                            portid.setText("");
                        }
                    }else
                    {
                        Toast.makeText(getApplicationContext(), "Incorrect Port ID", Toast.LENGTH_LONG);
                        portid.setText("");

                    }
                }catch(Exception e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.toString(),
                               Toast.LENGTH_SHORT).show();
                }}
                }
    });

      }
    protected void showMessage(String string, String string2) {
        // TODO Auto-generated method stub
            Builder builder=new Builder(this);
            builder.setCancelable(true);
            builder.setTitle(string);
            builder.setMessage(string2);
            builder.show();
    }
  }

my JSON Code is

JSONParse.java

public class JSONParser {

  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString().substring(0, sb.toString().length()-1);
         Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) 
    {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

    }

 }

my php code

login.php

   <?php

   $response = array();

   // check for required fields
   if (isset($_GET['portid'])  ) {

  $portid = $_GET['portid'];

   // include db connect class
  require_once __DIR__ . '/db_connect.php';

  // connecting to db
  $db = new DB_CONNECT();

  // mysql inserting a new row
  $result = mysql_query("select portid,name,fullname,relativename from port where portid = '$portid'");

  $row = mysql_fetch_array($result);
  if($row["portid"]== $portid)
  {
        $reply = array();
        $reply["portid"]= $row["portid"];
        $reply["name"]=$row["name"];
        $reply["fullname"]=$row["fullname"];
        $reply["relativename"]=$row["relativename"];
        $response["reply"] = array();
        array_push($response["reply"], $reply);
        $response['success'] = 1;
        $response['message'] = "Query";

       // echoing JSON response
       echo json_encode($response);
   }
   else {
     // failed to insert row
      $response["success"] = 0;
      $response["message"] = "Oops! An error occurred.";

      // echoing JSON response
      echo json_encode($response);
     }
  } 
  else {
     // required field is missing
     $response["success"] = 0;
     $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
   } 

 ?>

my program is running without any error on my emulater but after installing it into the mobile device m facing problem that is android.os.networkonmainthreadexception

please help me with this.

Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
  • i think the problem must b occur due to this line private static String url_login = "http://10.0.2.2/CramerA/login.php"; coz m using mysql database with ip 10.209.19.174 – ANITA SATPUTE Mar 20 '15 at 08:12
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Maveňツ Mar 20 '15 at 08:15

1 Answers1

0

android.os.networkonmainthreadexception occur if our app use network in main thread. For solve this problem use asynctask for fetch data from webservice or use StrictMode in activity

Santosh
  • 159
  • 1
  • 3
  • 7