0

I wants to check location exists in localhost , if the location exist or not, it will response to system and get the message(toast), but My Apps get force stop when i run, i don't know why, and where is my fault on my code.

This is my main code

public class SetLocationActivity extends Activity implements OnClickListener{

    private JSONParser jsonParser;
    private static String ServerURL="http://myurl/asset"; 
    private static String location_tag ="location";
    private String stats = null;
    Button go;
    EditText location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_location);
        location = (EditText)findViewById(R.id.edit_location);
        go = (Button)findViewById(R.id.btn_go);
        go.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        //Call class JSONParser
        jsonParser = new JSONParser();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag",location_tag));
        params.add(new BasicNameValuePair("loc",location.getText().toString()));
        JSONObject json = jsonParser.getJSONFromUrl(ServerURL, params);

        try {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;

            stats = json.getString("lo");
            if(stats != null) {
                CharSequence text = "List Location in"+stats;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            } else {
                CharSequence text = "Location not found";
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }       
        }catch(JSONException e) {
            //TODO Auto-Generated catch block
            e.printStackTrace();
        }
    }

and this is my JSONParser code

public class JSONParser {

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

    //Constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

            // Making HTTP request 
            try { 
                // 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();

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

and this is my logcat

01-05 16:37:23.382: E/AndroidRuntime(1096): FATAL EXCEPTION: main
01-05 16:37:23.382: E/AndroidRuntime(1096): android.os.NetworkOnMainThreadException
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.IoBridge.connect(IoBridge.java:112)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.Socket.connect(Socket.java:842)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.example.assetscanner.JSONParser.getJSONFromUrl(JSONParser.java:84)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.example.assetscanner.SetLocationActivity.onClick(SetLocationActivity.java:54)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.view.View.performClick(View.java:4162)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.view.View$PerformClick.run(View.java:17082)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Handler.handleCallback(Handler.java:615)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Looper.loop(Looper.java:137)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.app.ActivityThread.main(ActivityThread.java:4867)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.lang.reflect.Method.invoke(Method.java:511)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at dalvik.system.NativeStart.main(Native Method)

on this logcat above the main errors i think is "android.os.NetworkOnMainThreadException", i have searched about that's error, someone says using AsyncTask or StrictMode to this problem. but i don't know where i have to put the AsyncTask code and how?

And i want to know where is fault in my code, it's on main code or JSONParser code.

Please helps me for this problem, Thank's for your attentions

Blackrose
  • 25
  • 1
  • 6

1 Answers1

1

For doing long time taking operation we must use another thread from ui thread. Use Async Task fornetwork relation opeartion. It will not block your ui updation.

Happy Coding

Varun Vishnoi
  • 980
  • 1
  • 9
  • 32