将微调器项存储在字符串值中

时间:2015-07-07 14:28:32

标签: java android xml android-layout android-studio

我创建了一个连接到远程数据库的应用程序。数据库中的项目通过MainActivity类中的微调器显示。我想在一个单独的类(Map.java)和XML页面(map.xml)中显示所选项目,所以我在Map.java中使用此代码来尝试获取所选项目并显示它:

    Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
    String text = mySpinner.getSelectedItem().toString();
    EditText e = (EditText) findViewById (R.id.editText1);
    e.setText(text);

要显示此值,我在map.xml文件中创建了一个EditText:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:text="@string/text"
    android:id="@+id/editText1"
    android:layout_alignBottom="@+id/textView"
    android:layout_toRightOf="@+id/textView"
    android:layout_alignRight="@+id/imageView"
    android:layout_alignEnd="@+id/imageView" />

android:input_type="text"是我创建的字符串值:

<string name="text"> %s </string>

但每当我打开地图页面时,我的应用程序崩溃了。有人可以告诉我哪里出错了吗? 这里是MainActivity和Map.java的所有代码

MainActivity

package com.example.cillin.infoandroidhivespinnermysql;

import java.util.ArrayList;
..

public class MainActivity extends Activity implements OnItemSelectedListener        {

private Button btnAddNewCategory;
private TextView txtCategory;
public Spinner spinnerFood;

// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;

// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://192.168.1.4/food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://192.168.1.4/food_api/get_categories.php";

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

    btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
    spinnerFood = (Spinner) findViewById(R.id.spinFood);
    txtCategory = (TextView) findViewById(R.id.txtCategory);

    categoriesList = new ArrayList<Category>();

    // spinner item select listener
    spinnerFood.setOnItemSelectedListener(this);

    // Add new category click event
    btnAddNewCategory.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (txtCategory.getText().toString().trim().length() > 0) {

                // new category name
                String newCategory = txtCategory.getText().toString();

                // Call Async task to create new category
                new AddNewCategory().execute(newCategory);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter category name", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    new GetCategories().execute();

}

/**
 * Adding spinner data
 * */
private void populateSpinner() {
    List<String> lables = new ArrayList<String>();

    txtCategory.setText("");

    for (int i = 0; i < categoriesList.size(); i++) {
        lables.add(categoriesList.get(i).getName());
    }

    // Creating adapter for spinner
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, lables);

    // Drop down layout style - list view with radio button
    spinnerAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinnerFood.setAdapter(spinnerAdapter);

    //spinnerValue = spinnerFood.getSelectedItem().toString();
}

/**
 * Async task to get all food categories
 * */
private class GetCategories extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Fetching food categories..");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray categories = jsonObj
                            .getJSONArray("categories");

                    for (int i = 0; i < categories.length(); i++) {
                        JSONObject catObj = (JSONObject) categories.get(i);
                        Category cat = new Category(catObj.getInt("id"),
                                catObj.getString("name"));
                        categoriesList.add(cat);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("JSON Data", "Didn't receive any data from server!");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        populateSpinner();
    }

}

/**
 * Async task to create a new food category
 * */
private class AddNewCategory extends AsyncTask<String, Void, Void> {

    boolean isNewCategoryCreated = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Creating new category..");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(String... arg) {

        String newCategory = arg[0];

        // Preparing post params
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", newCategory));

        ServiceHandler serviceClient = new ServiceHandler();

        String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
                ServiceHandler.POST, params);

        Log.d("Create Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                boolean error = jsonObj.getBoolean("error");
                // checking for error node in json
                if (!error) {
                    // new category created successfully
                    isNewCategoryCreated = true;
                } else {
                    Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("JSON Data", "Didn't receive any data from server!");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        if (isNewCategoryCreated) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // fetching all categories
                    new GetCategories().execute();
                }
            });
        }
    }

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
                           long id) {
    Toast.makeText(
            getApplicationContext(),
            parent.getItemAtPosition(position).toString() + " Selected" ,
            Toast.LENGTH_LONG).show();

}

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

}

Map.java

package com.example.cillin.infoandroidhivespinnermysql;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class Map extends Activity {

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);


    //This page layout is located in the menu XML file
    //SetContentView links a Java file, to its XML file for the layout
    setContentView(R.layout.map);

    /*TextView.setText(spinnerValue);
    TextView spinv = (TextView)findViewById(R.id.textView2);
    spinv.setText(getspin());
    spinv = getspin();*/

    Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
    String text = mySpinner.getSelectedItem().toString();
    EditText e = (EditText) findViewById (R.id.editText1);
    e.setText(text);


    Button mainm = (Button)findViewById(R.id.mainmenu);
    mainm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //This button is linked to the map page
            Intent i = new Intent(Map.this, MainMenu.class);

            //Activating the intent
            startActivity(i);
        }
    });
}

}

任何帮助都将非常感谢!!

以下是崩溃时我的logcat中的错误:

  E/DatabaseUtils﹕ Writing exception to parcel
    java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
            at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:14643)
            at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2469)
            at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:688)
            at android.content.ContentProvider$Transport.call(ContentProvider.java:325)
            at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:275)
            at android.os.Binder.execTransact(Binder.java:404)


    E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.cillin.infoandroidhivespinnermysql, PID: 14691
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cillin.infoandroidhivespinnermysql/com.example.cillin.infoandroidhivespinnermysql.Map}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
            at      

android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.cillin.infoandroidhivespinnermysql.Map.onCreate(Map.java:34)
        at android.app.Activity.performCreate(Activity.java:5426)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

我猜你在Map.class中得到了NullPointerException

Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);

您获得了对Spinner的引用,然后您尝试获取所选项目,然后将该项目转换为字符串。据我所知,你实际上没有向微调器添加任何项目。我的猜测是你试图访问微调器中的一个对象,因为它不存在,它返回null。然后尝试在null对象上调用一个方法并获得一个NPE。

这只是猜测。堆栈跟踪在尝试诊断时非常有用。

我认为你出错的地方是你在MainActivity中填充微调器,然后期望能够从不同的活动中选择来自该微调器的项目。这不是它的工作原理。 Map.class将无法引用MainActivity.class中的任何内容。您可以尝试将对象从MainActivity.class传递给Map.class或使用不同的传递数据的方法,但尝试从Map.class中引用MainAcitivity.class中的数据将不起作用。

编辑: 如果您只想将MainActivity.class中的String传递给Map.class,可以将该字符串作为'extra'添加到用于启动Map.class的intent中。

在MainActivity.class代码中。选择微调器中的项目时,使用putExtra()方法创建一个intent并将该字符串设置为extra。您需要提供一个基本上标记额外的密钥,以便您可以在接收活动和要发送的字符串中识别它。

Intent intent = new Intent(this, Map.class);
intent.putExtra("KEY_SPINNER_STRING", variableRepresentingString);
startActivity(intent);

在Map.class活动中,在onCreate()方法中,您需要接收intent,检查extra,然后解压缩额外的。然后你将拥有String。

onCreate(Bundle savedInstanceState) {
    String spinnerString;
    if (getIntent() != null && getIntent().getExtras() != null) {
        Bundle bundle = getIntent().getExtras();
        if (bundle.getString("KEY_SPINNER_STRING") != null) {
            spinnerString = bundle.getString("KEY_SPINNER_STRING");
        }
    }
}

如果一切正确完成,String将从MainActivity.class传递并由Map.class

接收