Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8623157
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T07:13:06+00:00 2026-06-12T07:13:06+00:00

Possible Duplicate: Android HttpClient : NetworkOnMainThreadException I am working on an application that is

  • 0

Possible Duplicate:
Android HttpClient : NetworkOnMainThreadException

I am working on an application that is making requests, and the app works fine, up until I have to make a request to the server. I am using the same code as it was written before for the same app, but this has been revised.

Fragment Class That Handles Click:

import org.json.JSONException;
import org.json.JSONObject;
import org.myapp.app.utils.API;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentStudentLogin extends Fragment implements OnClickListener {
EditText uN, pW;
Button signin;

private API api;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_login, container, false);
    signin = (Button)v.findViewById(R.id.s_sign_in);
    signin.setOnClickListener(this);

    uN = (EditText)v.findViewById(R.id.f_t_s_username);
    pW = (EditText)v.findViewById(R.id.f_t_s_password);

    api = new API();

    return v;

    }

    public void onClick(View v){
    switch(v.getId())
    {
        case R.id.s_sign_in:
            String user = uN.getText().toString();
            String pass = pW.getText().toString();
            if(user.length()==0){
                PopIt("Please enter your username.");
            } else if(pass.length()==0){
                PopIt("Please enter your password.");
            } else {
                try {
            JSONObject json;
                    json = api.login(user, pass);
        if(json == null || json.isNull("status")){
            PopIt(getString(R.string.error_network));
        } else {
                        PopIt(json.getString("msg"));
                    }
                } catch (JSONException e){ }
            }
        break;
        }
    }

    public void PopIt(String msg){
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
}

Class that Click makes a call to:

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import org.myapp.app.utils.JSONParser;

public class API
{
    private JSONParser jsonParser;
    private static String serverURL = "http://mydomain.com/api/device/login";

    public API(){
        jsonParser = new JSONParser();
    }

    public JSONObject login(String uN, String pW)
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", uN));
        params.add(new BasicNameValuePair("password", pW));
        JSONObject json = jsonParser.getJSONFromUrl(serverURL, params);
        return json;
    }

Class that Processes Requests:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    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;

    }
}

LogCat

10-02 19:40:23.734: E/AndroidRuntime(4401): FATAL EXCEPTION: main
10-02 19:40:23.734: E/AndroidRuntime(4401): android.os.NetworkOnMainThreadException
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.JSONParser.getJSONFromUrl(JSONParser.java:42)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.API.studentLogin(API.java:26)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.FragmentStudentLogin.onClick(FragmentStudentLogin.java:52)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View.performClick(View.java:3511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View$PerformClick.run(View.java:14109)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.handleCallback(Handler.java:605)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Looper.loop(Looper.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.app.ActivityThread.main(ActivityThread.java:4424)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invokeNative(Native Method)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invoke(Method.java:511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at dalvik.system.NativeStart.main(Native Method)

Like I said, This code worked before, “Class that Click makes a call to:”, and “Class that Processes Requests:” sections, I have used before with no problems. Android API 16 is being used on a 7″ Tablet. Would greatly appreciate any help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T07:13:07+00:00Added an answer on June 12, 2026 at 7:13 am

    The exception message is pretty clear. Android 4.0 and above will not let you make a network call on the main (UI) thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Android Unknown Command 'crunch' I have been using eclipse just fine but
Possible Duplicate: Android HttpClient and HTTPS I want to write app on Android which
Possible Duplicate: android.os.NetworkOnMainThreadException When I run the my android application, I got android.os.NetworkOnMainThreadException, what
Possible Duplicate: Android Button: set onClick background image change with XML? I need that
Possible Duplicate: Android Launch an application from another application I am having a problem
Possible Duplicate: Android SMS Receiver not working I am in the beginning stages of
Possible Duplicate: Android Launch an application from another application I want to start Another
Possible Duplicate: Why does Android app run in small window on tablet emulator? i
Possible Duplicate: How can I create a multilingual android application? I am creating application
Possible Duplicate: Using ZXing to create an android barcode scanning app I know it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.