繁体   English   中英

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

[英]Android unable to launch the app in emulator

我是移动应用程序开发的新手。 我正在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"}]}

现在转向我的Android部分

以下是我的Config file

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

}

主要活动

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); 我低于错误

在此处输入图片说明

我知道我已经调查了许多问题,但仍然无法解决问题。

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

尝试这个:

import android.widget.AdapterView.OnItemSelectedListener;

现在:

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener

在您的活动中:

spinner.setOnItemSelectedListener(this)

您还必须重写以下方法:

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

public void onNothingSelected(AdapterView<?> parent) {

}

尝试导入android.widget.AdapterView.OnItemSelectedListener; 这是Eclipse的一个共同的问题,因为在提到岗位

使用android studio非常容易。

步骤1 :将光标放在红线词上(这里是“ this”)

第2步 :按Alt + Enter键

步骤3 :选择Make OnItemSelectedListener

步骤4 :在下一个对话框中按确定按钮。

通常这类问题可以用谷歌搜索。

首先,我们必须查看日志。 其次,我们必须找到问题所在。

在您的日志中,您可以看到“ 标签引起,后跟异常”。

这里是第64行的ClassCastException

只是谷歌它的例外。 干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM