как извлечь данные таблицы phpmyadmin в текстовое представление или список просмотра android студийного приложения - PullRequest
0 голосов
/ 26 февраля 2020

У меня есть таблица с именем demo_table в phpmyadmin с двумя именами полей и адресами электронной почты. Я хочу получить все данные из phpmyadmin в android текстовое представление или просмотр списка приложения, вызвав страницу php в приложении android. Я загрузил свой код ниже .. пожалуйста go через него и помогите мне.

  • MainActivity. java file

        package com.example.display;
        import java.io.IOException;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.util.EntityUtils;
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
        import android.app.Activity;
        import android.content.Context;
        //import android.content.Intent;
        //import android.net.Uri;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.ProgressBar;
        import android.widget.TextView;
    
        public class MainActivity extends Activity {<br>
            TextView resultname,resultemail;
            JSONObject json = null;
            String str = "";
            HttpResponse response;
            Context context;
            //ProgressBar progressbar;
            Button button;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
    
                //progressbar = (ProgressBar)findViewById(R.id.progressBar1);
                resultname = (TextView)findViewById(R.id.textViewName);
                resultemail = (TextView)findViewById(R.id.textViewEmail);
                button = (Button)findViewById(R.id.button1);
                //progressbar.setVisibility(View.GONE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        //progressbar.setVisibility(View.VISIBLE);
                        new GetTextViewData(context).execute();
                    }
                });
            }
    
            private class GetTextViewData extends AsyncTask<Void, Void, Void>
            {
                public Context context;
                public GetTextViewData(Context context)
                {
                    this.context = context;
                }
                @Override
                protected void onPreExecute()
                {
                    super.onPreExecute();
                }
                @Override
                protected Void doInBackground(Void... arg0)
                {
                    HttpClient myClient = new DefaultHttpClient();
                    HttpPost myConnection = new HttpPost("http://192.168.1.7:8080/Android/display.php");
                    try {
                        response = myClient.execute(myConnection);
                        str = EntityUtils.toString(response.getEntity(), "UTF-8");
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try{
                        JSONArray jArray = new JSONArray(str);
                        json = jArray.getJSONObject(0);
                    } catch ( JSONException e) {
                        e.printStackTrace();
                    }
                    catch (Exception e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }
                protected void onPostExecute(Void result)
                {
                    try {
                        resultname.setText(json.getString("ServerData Name"));
                        resultemail.setText(json.getString("ServerData Email"));
    
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //Hiding progress bar after done loading TextView.
                    //progressbar.setVisibility(View.GONE);
                }
            }
        }
    
  • activity_main. xml file

            <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context="com.example.display.MainActivity">
    
                <TextView
                    android:id="@+id/textViewName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TextView Text Before Load From Server"
                    android:textSize="25dp"
                    android:textColor="#000"
                    android:layout_gravity="center"
                    android:layout_marginTop="58dp" />
    
                <TextView
                    android:id="@+id/textViewEmail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Email Before Load From Server"
                    android:textSize="25dp"
                    android:textColor="#000"
                    android:layout_gravity="center"
                    android:layout_marginTop="58dp" />
    
                <Button
                    android:id="@+id/button1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="Fetch Data" />
    
                <!--<ProgressBar
                    android:id="@+id/progressBar1"
                    style="?android:attr/progressBarStyle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="22dp"
                    android:visibility="gone"/>-->
    
            </LinearLayout>
    
  • get_receive. php file

    <?php
    $HostName = "localhost";
    $HostUser = "root";
    $HostPass = "";
    $DatabaseName = "demo_db";
    $conn = new mysqli($HostName,$HostUser,$HostPass,$DatabaseName);
    if($conn->connect_error)
    {
        die("Connection failed:".$conn->connect_error);
    }
    $result=$conn->query("select name,email from demo_table"); 
          if($result->num_rows>0)
           {    
            while($rows= $result->fetch_assoc()) 
              {  
                    $json=json_encode($rows);
              }
            }else{
                echo "No results";
            }     
            echo $json;
            $conn->close();
    ?>
    

После запуска приложения при нажатии кнопки подтверждения приложение останавливается. Я хочу получить имя из таблицы phpmyadmin в первом текстовом просмотре и электронную почту во втором текстовом просмотре. В моей таблице есть три поля (id (автоинкремент, имя, адрес электронной почты), пожалуйста, помогите мне решить эту проблему

1 Ответ

0 голосов
/ 26 февраля 2020

Использовать библиотеку, например, для дооснащения и для отображения данных в android представлении, использовать вид переработчика и подход с использованием карт с адаптером. go через это https://www.androidhive.info/2016/01/android-working-with-recycler-view

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...