我目前正在android studio中开发一个应用程序。我的应用程序的目标是让一个页面(MainActivity.java和amp; activityMain.xml)显示一个微调器。此微调器中的项是来自远程数据库的项。当用户选择此微调器中的项目时,我希望所选项目显示在单独的页面中(Map.java map.xml)。 我在MainActivity中使用了一个putExtra方法将所选项存储到字符串变量中:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
然后在我的Map类中,我使用getExtras调用该字符串:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
我可以将此字符串从MainActivity成功传递给Map。我的问题是当我尝试显示此字符串时,我运行应用程序时不会出现在XML页面或手机上。我使用以下代码尝试显示字符串:
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
有人可以告诉我哪里出错了吗?
这是我的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;
//public String spinnerValue;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://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
* */
public 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);
//String text = 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();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
@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;
/**
* Created by cillin on 06/07/2015.
*/
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);
/*Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);*/
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
/*if (getIntent() != null && getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
if (bundle.getString("SPINNER_KEY") != null) {
spinnerString = bundle.getString("SPINNER_KEY");
}
}*/
//String a = "ddd";
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
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);
}
});
}
}
这是我的map.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="@+id/imageView"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/map_image"
android:contentDescription="@string/map"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<Button
android:id="@+id/mainmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="140dp"
android:layout_marginTop = "450dp"
android:text="Main Menu" />
<TextView
android:layout_width="200dp"
android:layout_height="20dp"
android:id="@+id/textView"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/imageView"
android:layout_alignEnd="@+id/imageView" />
</RelativeLayout>
答案 0 :(得分:0)
你必须使用getIntent().getStringExtra("STRING_I_NEED");
getIntent.getExtras()
时, Bundle
才有效
答案 1 :(得分:0)
我修好了它:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
我改变了#34; STRING_I_NEED&#34;到&#34; SPINNER_KEY&#34;