0

I am newbie in native android development. I am working on android studio. I have created a web service api using yii, also i have created two tables in mysql named Users and Activity, Entered some data into the User table like below

enter image description here

Now i want is whenever user enters the id of the user then the specific username should be shown.

For this i followed this stack link and made layout

 <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName|number"
    android:ems="10"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/etId"
    style="@style/Widget.AppCompat.EditText" />

<Button
    android:text="Submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:id="@+id/btn_Submit"
    android:layout_alignBottom="@+id/etId" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="53dp"
    android:id="@+id/textView"
    android:textAppearance="@style/TextAppearance.AppCompat.Display1"
    android:layout_below="@+id/etId"
    android:layout_centerHorizontal="true" />

I want to show the name on the text.

As per the link i followed it but unable to view my required result.

public class MainActivity extends AppCompatActivity {

String URL = "http://localhost:8000/app/web/users/";
String result = "";

TextView tv; public static final String LOG_TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    final EditText editText = (EditText)findViewById(R.id.etId);

    /*editText.setOnClickListener(new EditText.OnClickListener(){

        @Override
        public void onClick(View v) {
            editText.setText(" ");
        }
    });
    */
    final Button button = (Button)findViewById(R.id.btn_Submit);

    button.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            String query = editText.getText().toString();
            callWebService(query);
        }
    });

}

private void callWebService(String q) {

    HttpClient httpclient = new DefaultHttpClient();

    HttpGet request = new HttpGet(URL + q);

    ResponseHandler<String> handler = new BasicResponseHandler();

    try
    {
        result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpclient.getConnectionManager().shutdown();
    tv = (TextView)findViewById(R.id.textView);

    Toast.makeText(LOG_TAG, "Hi", result).show();
    //tv.append("Hi ", result, ":" );
}

Update 1

Below is the error which i get when i tap the button

android.os.NetworkOnMainThreadException
                                                                              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                                                                              at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
                                                                              at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                                              at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                                              at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
                                                                              at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
                                                                              at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
                                                                              at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
                                                                              at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
                                                                              at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
                                                                              at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
                                                                              at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
                                                                              at com.example.accurat.webservice.MainActivity$1.onClick(MainActivity.java:53)
                                                                              at android.view.View.performClick(View.java:4780)
                                                                              at android.view.View$PerformClick.run(View.java:19866)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

And it comes at point

` button.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            String query = editText.getText().toString();
            callWebService(query);
        }
    });`

Update 2

By following this link i have done the following

 if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

Now my app won't crash but it just show me HI and not the requested data

While debugging it i got exception org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8000 refused

While when i request it on my browser it does show me the required result as show in below image

enter image description here

NOTE:

I am testing it on emulator.

Any help would be highly appreciated.

Community
  • 1
  • 1
Moeez
  • 494
  • 9
  • 55
  • 147

3 Answers3

0

NetworkOnMainThreadException occurs only when you are using web operation on main thread.Run your code in AsyncTask or in other Thread:

new Thread(new Runnable(){
  @Override
  public void run() {
    // Do network action in this function
  }
}).start();

Check this out for more on NetworkOnMainThreadException.

NOTE-

In simple words,

DO NOT DO NETWORK WORK IN THE UI THREAD

But

If you use simple thread ,When you get something from Network response and want to show it on your view (like display response message in TextView), you need to return back to the UI thread.

If you don't do it, you will get ViewRootImpl$CalledFromWrongThreadException.

So , for newbie i would suggest AssyncTask .

UPDATE

http://localhost

The above host is already occupied by the emulator in which you are running the code. If you want to access the local host of your computer then use the IP Address as http://yourip:8080/.

For more details, please refer this link.

Community
  • 1
  • 1
karanatwal.github.io
  • 3,613
  • 3
  • 25
  • 57
  • Not working my app stuck when i tap on `submit button` – Moeez Feb 07 '17 at 10:04
  • While in `logcat` i am getting warnings for `Suspending all threads` and `org.apache.http.conn.HttpHostConnectException: Connection to http://My_ip:8000 refused` – Moeez Feb 07 '17 at 10:06
  • I have posted a new [question](http://stackoverflow.com/questions/42088579/progress-dialog-keeps-on-displaying-in-android-studio) please see it – Moeez Feb 07 '17 at 11:35
  • You already have an answer there to your new question. put a check for buffer if it comes null. And, in future keep in mind Do Network work in background Task. – karanatwal.github.io Feb 07 '17 at 12:03
0

you should:

  1. Apply Internet permission on Manifest.xml
  2. Network should not run on Main thread.you should do it on other thread
  3. you can choose third party lib to simplify network request,like Volley or Retrofit
0

Android usually doesnot support localhost as the url since most computers are connected through wifi or other network. try to replace localhost with the IPADDRESS of your system. Like:

String URL = "http://192.168.1.1:8000/app/web/users/"; //replace 192.168.1.1 with your ip address
M.Waqas Pervez
  • 2,492
  • 2
  • 19
  • 33