简体   繁体   English

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

[英]Storing a spinner item in a string value

I have created an app that is connected to a remote database. 我创建了一个连接到远程数据库的应用程序。 The items in the database are displayed through a spinner in my MainActivity class. 数据库中的项目通过MainActivity类中的微调器显示。 I want to display the selected item in a separate class(Map.java) and XML page(map.xml), So I used this code in Map.java to try get the selected item and display it: 我想在单独的类(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);

To display this value I created an EditText in my map.xml file: 为了显示此值,我在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" />

The android:input_type="text" is a string value I created: android:input_type="text"是我创建的字符串值:

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

But whenever I open the map page my app crashes. 但是,每当我打开地图页面时,我的应用就会崩溃。 Could someone please tell me where I am going wrong? 有人可以告诉我我要去哪里错吗? Here all of my code for MainActivity and Map.java 这是我用于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 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 { 公共类Map扩展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);
        }
    });
}

}

Any help would be much appreciated!! 任何帮助将非常感激!!

Here are the errors in my logcat when is crashes: 这是崩溃时我的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)

I'm guessing that you're getting a NullPointerException in your Map.class 我猜你在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);

You get a reference to Spinner, then you try to get the selected item and then convert that item to a string. 您获得对Spinner的引用,然后尝试获取选定的项目,然后将该项目转换为字符串。 As far as I can tell you haven't actually added any items to the spinner. 据我所知,您实际上尚未向微调器添加任何项目。 My guess is that you are trying to access an object in the spinner and since it doesn't exist it returns null. 我的猜测是,您正在尝试访问微调器中的对象,由于该对象不存在,它返回null。 Then you try to call a method on the null object and get an NPE. 然后,您尝试在空对象上调用方法并获得NPE。

This is just a guess. 这只是一个猜测。 A stacktrace is very helpful in trying to diagnose this. 堆栈跟踪对于尝试诊断此问题非常有用。

Where I think you're going wrong is that you populate the spinner in MainActivity and then expect to be able to select an item from that spinner from a different activity. 我认为您要出错的地方是您在MainActivity中填充了微调器,然后期望能够从其他活动中的该微调器中选择一个项目。 This isn't how it works. 这不是它的工作方式。 Map.class won't be able to reference anything in MainActivity.class. Map.class将无法在MainActivity.class中引用任何内容。 You could try passing the object from MainActivity.class to Map.class or use a different method of passing data, but trying to reference data in MainAcitivity.class from Map.class won't work. 您可以尝试将对象从MainActivity.class传递到Map.class,或使用其他方法传递数据,但是尝试从Map.class引用MainAcitivity.class中的数据将不起作用。

Edit: If you just want to pass a String from MainActivity.class to Map.class you can add the string as an 'extra' to the intent that you use to start Map.class. 编辑:如果只想将String从MainActivity.class传递到Map.class,则可以将字符串作为“额外”添加到用于启动Map.class的意图中。

In your MainActivity.class code. 在您的MainActivity.class代码中。 When the item from the spinner is selected, create an intent and set the string as an extra using the putExtra() method. 选择微调器中的项目后,创建一个意图,并使用putExtra()方法将字符串设置为额外字符串。 You will need to supply a key that basically tags the extra so you can identify it in the receiving activity and the string you want to send. 您将需要提供一个基本上可以标记多余字符的密钥,以便您可以在接收活动和要发送的字符串中识别它。

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

In the Map.class activity, in the onCreate() method you will need to receive the intent, check for the extra, then unpack the extra. 在Map.class活动中,您需要在onCreate()方法中接收该意图,检查是否有多余的东西,然后将多余的东西拆包。 Then you will have the 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");
        }
    }
}

If everything is done correctly the String will be passed from MainActivity.class and received by Map.class 如果一切都正确完成,则字符串将从MainActivity.class传递并由Map.class接收

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

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