【问题标题】:Get username based on user ID using REST api in android studio在android studio中使用REST api根据用户ID获取用户名
【发布时间】:2017-06-23 13:04:46
【问题描述】:

我是原生安卓开发的新手。我正在处理android studio。我使用yii 创建了一个web service api,还在mysql 中创建了两个名为UsersActivity 的表,在User 表中输入了一些数据,如下所示

现在我想要的是每当用户输入用户的id 时,应该显示特定的username

为此,我遵循了这个堆栈link 并进行了布局

 <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" />

我想在文本上显示名称。

根据我关注的链接,但无法查看我需要的结果。

public class MainActivity extends AppCompatActivity {

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

TextView 电视; 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, ":" );
}

更新 1

以下是我点击按钮时出现的错误

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)

它来了

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

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

更新 2

通过关注link 我已经完成了以下操作

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

现在我的应用不会崩溃,但它只会显示 HI 而不是请求的数据

调试时出现异常 org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8000 refused

当我在浏览器上请求它时,它会向我显示所需的结果,如下图所示

注意:

我正在模拟器上测试它。

任何帮助将不胜感激。

【问题讨论】:

  • 你遇到了什么错误?
  • 您的基于 yii 的 API 是否按预期工作?
  • @M.WaqasPervez 请看我的update 1
  • @Shadow 是的,我已经在ARC 上对其进行了测试,GET 方法运行良好。现在我只想使用GET 方法。
  • 首先尝试硬编码的 url。也许你拼错了什么。

标签: android mysql android-studio yii


【解决方案1】:

NetworkOnMainThreadException 仅在您在主线程上使用 web 操作时出现。在AsyncTask 或其他Thread 中运行您的代码:

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

NetworkOnMainThreadException上查看更多信息。

注意-

简单来说,

不要在 UI 线程中进行网络工作

但是

如果您使用简单线程,当您从网络响应中获取某些内容并希望将其显示在您的视图中(例如在 TextView 中显示响应消息)时,您需要返回到 UI 线程。

如果你不这样做,你会得到ViewRootImpl$CalledFromWrongThreadException

所以,对于新手,我建议AssyncTask

更新

http://localhost

上面的主机已经被运行代码的模拟器占用了。如果要访问计算机的本地主机,请使用 IP 地址 http://yourip:8080/.

更多详情请参考link

【讨论】:

  • 点击submit button时我的应用卡住了
  • logcat 中,我收到Suspending all threadsorg.apache.http.conn.HttpHostConnectException: Connection to http://My_ip:8000 refused 的警告
  • 我发了一个新的question请看
  • 您的新问题已经有了答案。如果缓冲区为空,请检查缓冲区。并且,将来请记住在后台任务中进行网络工作。
【解决方案2】:

你应该:

  1. 对 Manifest.xml 应用 Internet 权限
  2. 网络不应该在主线程上运行。你应该在其他线程上运行
  3. 您可以选择第三方库来简化网络请求,例如 Volley 或 Retrofit

【讨论】:

    【解决方案3】:

    Android 通常不支持localhost 作为 url,因为大多数计算机都是通过 wifi 或其他网络连接的。尝试用您系统的IPADDRESS 替换localhost。喜欢:

    String URL = "http://192.168.1.1:8000/app/web/users/"; //replace 192.168.1.1 with your ip address
    

    【讨论】:

    • 点击submit button时我的应用卡住了
    猜你喜欢
    • 1970-01-01
    • 2023-01-05
    • 2020-08-03
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多