java - Android 无法在模拟器中启动该应用程序

标签 java php android mysql android-studio

我是移动应用开发的新手。我正在开发 android studio。我在mysql DB 中创建了两个表,其中一个是users,另一个是activity。现在我正在使用 users 表。我的任务是制作一个 app,其中应该有一个 dropdown 并且所有用户名都在其中。当用户选择任何名称时,将显示该用户的 id

为此,我创建了一个 php 文件,我在其中返回了一个 json 结果。

下面是我的php代码

$sql = "SELECT * FROM users";


$r = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($r)){
   array_push($result,array(
    'Id'=>$row['Id'],
    'Name'=>$row['Name']
   ));
}

  echo json_encode(array('result'=>$result));

  mysqli_close($con);

下面是上面代码的结果

{"users":[{"Id":"1","Name":"Faisal"},{"Id":"2","Name":"Salman"},{"Id":"3","Name":"Asim"},{"Id":"4","Name":"Asad"},{"Id":"5","Name":"Mateen"}]}

现在转向我的安卓部分

下面是我的配置文件

public class Config {

//JSON URL
public static final String DATA_URL = "http://10.0.2.2:8000/MobileApp/index.php";

//Tags used in the JSON String

public static final String TAG_NAME = "Name";

public static final String TAG_ID = "Id";

//JSON array name
public static final String JSON_ARRAY = "users";

}

主 Activity

public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {

  //Declaring an Spinner
 private Spinner spinner;

//An ArrayList for Spinner Items
private ArrayList<String> users;

//JSON Array
private JSONArray result;

//TextViews to display details
private TextView textViewResult;



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


    //Initializing the ArrayList
    users = new ArrayList<String>();

    //Initializing Spinner
    spinner = (Spinner)findViewById(R.id.spinner);


    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself
    // we are passing this to setOnItemSelectedListener

    spinner.setOnItemClickListener((AdapterView.OnItemClickListener) this);

    //Initializing TextView

    textViewResult = (TextView)findViewById(R.id.textView);

    //This method will fetch the data from the URL
    getData();
}

private void getData() {

    //Creating a string request
    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result = j.getJSONArray(Config.JSON_ARRAY);

                        //Calling method getStudents to get the students from the JSON Array
                        getUsers(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void getUsers(JSONArray j) {

    //Traversing through all the items in the json array
    for(int i =0; i<j.length(); i++)
    {
        try
        {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            users.add(json.getString(Config.TAG_NAME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

 //Setting adapter to show the items in the spinner

    spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_dropdown_item, users));
}

private void getUsers() {


}

//Method to get student name of a particular position
private String getName(int position)
{
    String name = "";
    try
    {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);
        //Fetching name from that object
        name = json.getString(Config.TAG_NAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}

//Method to get student Id of a particular position
private String getId (int postion)
{
    String Id="";
    try{
        JSONObject json = result.getJSONObject(postion);

        Id = json.getString(Config.TAG_ID);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return Id;
}

//this method will execute when we pic an item from the spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    //Appending the values to textview for a selected item

    textViewResult.append("Hi " + getName(position) + "Your ID is " + getId(position));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

    textViewResult.setText("");

}}

现在我使用 10.0.2.2 在模拟器中运行应用程序。当我运行该应用程序时,该应用程序崩溃并在 logcat 出现以下错误

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.accurat.webaccess/com.example.accurat.webaccess.MainActivity}: java.lang.ClassCastException: com.example.accurat.webaccess.MainActivity cannot be cast to android.widget.AdapterView$OnItemClickListener
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                             at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             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)
                                                                          Caused by: java.lang.ClassCastException: com.example.accurat.webaccess.MainActivity cannot be cast to android.widget.AdapterView$OnItemClickListener
                                                                             at com.example.accurat.webaccess.MainActivity.onCreate(MainActivity.java:64)
                                                                             at android.app.Activity.performCreate(Activity.java:5990)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                             at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             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) 

它命中 textViewResult = (TextView)findViewById(R.id.textView);

更新 1

通过使用 spinner.setOnItemClickListener(this); 我得到以下错误

enter image description here

我知道上面有很多问题,我已经调查过了,但我仍然无法解决问题。

我不知道是什么问题。任何帮助将不胜感激。

最佳答案

试试这个:

import android.widget.AdapterView.OnItemSelectedListener;

现在:

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener

在你的 Activity 中:

spinner.setOnItemSelectedListener(this)

您还必须重写以下方法:

 public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    //write your code
}

public void onNothingSelected(AdapterView<?> parent) {

}

关于java - Android 无法在模拟器中启动该应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223444/

相关文章:

php - 将两个数组合并为一个数组

java - 如何维护用户登录 session ?

java - 构建失败,出现异常 : Task '—' not found in root project

android - 单击按钮时我的 toast 不起作用,它强制关闭并重新启动主要 Activity

java - 仅从父级 <td> 获取文本

Java 抽象方法的通配符返回类型

java - 使用预定义的递归创建基本数学运算

php - Symfony2 中的策略模式

php - mysqli 获取数组返回 null 作为结果

Java 反射 getDeclaredMethod 抛出 NoSuchMethodException