Android无法在模拟器

时间:2017-02-14 10:18:04

标签: 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"}]}

现在转向我的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";

}

MainActivity

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

我知道有很多问题我已经调查了它们但仍然无法解决问题。

我不知道是什么问题。任何帮助都将受到高度赞赏。

3 个答案:

答案 0 :(得分:1)

试试这个:

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) {

}

答案 1 :(得分:1)

尝试导入android.widget.AdapterView.OnItemSelectedListener; 这是eclipse中常见的问题,如post

中所述

答案 2 :(得分:1)

使用android studio非常容易。

  

第1步:将光标放在红线上(此处为&#39;此&#39;)

     

第2步:按Alt + Enter键

     

第3步:选择Make OnItemSelectedListener

     

第4步:按下下一个对话框上的确定按钮。完成。

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

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

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

这里是第64行的ClassCastException

只是谷歌那个例外。欢呼声