在我的第一个Activity中,我有三个Spinner
和三个EditText
,我需要将所选数据传递给第二个活动并将它们解析为json对象。我在调用第二个活动时出现问题。感谢
第一项活动
public class AndroidspinnerActivity extends Activity
{
private ArrayList<Country> countryList;
EditText subjname, slperiod, sldate;
Spinner deptsp, degreesp, yearsp;
DatePicker datepicker;
void showToast(CharSequence msg)
{
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url = "http://10.0.2.2:8080/SpinnerJson/CountryServlet";
grabURL(url);
}
public void grabURL(String url)
{
Log.v("Android Spinner JSON Data Activity", url);
new GrabURL().execute(url);
}
private void displayCountries(String response)
{
JSONObject responseObj = null;
try
{
Gson gson = new Gson();
responseObj = new JSONObject(response);
JSONArray countryListObj = responseObj.getJSONArray("countryList");
countryList = new ArrayList<Country>();
String[] dept_array = new String[countryListObj.length()];
String[] degree_array = new String[countryListObj.length()];
String[] year_array = new String[countryListObj.length()];
for (int i = 0; i < countryListObj.length(); i++)
{
// add to country names array
dept_array[i] = countryListObj.getJSONObject(i).getString("deptname");
degree_array[i] = countryListObj.getJSONObject(i).getString("degree");
year_array[i] = countryListObj.getJSONObject(i).getString("year");
// get the country information JSON object
String countryInfo = countryListObj.getJSONObject(i).toString();
// create java object from the JSON object
Country country = gson.fromJson(countryInfo, Country.class);
// add to country array list
countryList.add(country);
}
deptsp = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dept_array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deptsp.setAdapter(adapter);
deptsp.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{}
public void onNothingSelected(AdapterView<?> parent)
{}
});
degreesp = (Spinner) findViewById(R.id.Spinner02);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, degree_array);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
degreesp.setAdapter(adapter1);
degreesp.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{}
public void onNothingSelected(AdapterView<?> parent)
{}
});
yearsp = (Spinner) findViewById(R.id.Spinner03);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, year_array);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yearsp.setAdapter(adapter2);
yearsp.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{}
public void onNothingSelected(AdapterView<?> parent)
{}
});
Button contbtn = (Button) findViewById(R.id.btn_continue);
contbtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// String sldeptdp = deptsp.getSelectedItem().toString();
// String sldegreedp = degreesp.getSelectedItem().toString();
// String slyeardp = yearsp.getSelectedItem().toString();
// String subjnamee = subjname.getText().toString();
// String sldatee = sldate.getText().toString();
// String slperiodd = slperiod.getText().toString();
// JSONObject jsonobject;
// jsonobject = new JSONObject();
// try
// {
// jsonobject.put(sldeptdp, "");
// jsonobject.put(sldegreedp, "");
// jsonobject.put(slyeardp, "");
// jsonobject.put(subjnamee, "");
// jsonobject.put(sldatee, "");
// jsonobject.put(slperiodd, "");
// showToast((jsonobject.toString(2)));
// }
// catch (JSONException ex)
// {}
onclickgo();
}
});
// subj name
subjname = (EditText) findViewById(R.id.edit_sub);
subjname.getText().toString();
// date
sldate = (EditText) findViewById(R.id.edit_date);
sldate.getText().toString();
slperiod = (EditText) findViewById(R.id.edit_period);
slperiod.getText().toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
String sldeptdp = deptsp.getSelectedItem().toString();
String sldegreedp = degreesp.getSelectedItem().toString();
String slyeardp = yearsp.getSelectedItem().toString();
String subjnamee = subjname.getText().toString();
String sldatee = sldate.getText().toString();
String slperiodd = slperiod.getText().toString();
Intent intent = new Intent(this, Parshingdata.class);
intent.putExtra("sldept", sldeptdp);
intent.putExtra("sldegree", sldegreedp);
intent.putExtra("slyear", slyeardp);
intent.putExtra("slsubjname", subjnamee);
intent.putExtra("sldate", sldatee);
intent.putExtra("slperiod", slperiodd);
startActivity(intent);
}
protected void onclickgo()
{
Intent i = new Intent(this, Parshingdata.class);
startActivity(i);
}
private class GrabURL extends AsyncTask<String, Void, String>
{
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private boolean error = false;
private ProgressDialog dialog = new ProgressDialog(AndroidspinnerActivity.this);
protected void onPreExecute()
{
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls)
{
String URL = null;
try
{
URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("fakeInput", "not in USE for this demo"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
}
else
{
// Closes the connection.
Log.w("HTTP1:", statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
catch (ClientProtocolException e)
{
Log.w("HTTP2:", e);
content = e.getMessage();
error = true;
cancel(true);
}
catch (IOException e)
{
Log.w("HTTP3:", e);
content = e.getMessage();
error = true;
cancel(true);
}
catch (Exception e)
{
Log.w("HTTP4:", e);
content = e.getMessage();
error = true;
cancel(true);
}
return content;
}
protected void onCancelled()
{
dialog.dismiss();
Toast toast = Toast.makeText(AndroidspinnerActivity.this, "Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String content)
{
dialog.dismiss();
Toast toast;
if (error)
{
toast = Toast.makeText(AndroidspinnerActivity.this, content, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
else
{
displayCountries(content);
}
}
}
}
第二项活动
public class Parshingdata extends Activity
{
void showToast(CharSequence msg)
{
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.takeattnd);
String sldept = getIntent().getExtras().getString("sldept");
String sldegree = getIntent().getExtras().getString("sldegree");
String slyear = getIntent().getExtras().getString("slyear");
String slsubjname = getIntent().getExtras().getString("slsubjname");
String slperiod = getIntent().getExtras().getString("slperiod");
String sldate = getIntent().getExtras().getString("sldate");
JSONObject jsonobject = new JSONObject();
try
{
jsonobject.put(sldept, "");
jsonobject.put(sldegree, "");
jsonobject.put(slyear, "");
jsonobject.put(slsubjname, "");
jsonobject.put(sldate, "");
jsonobject.put(slperiod, "");
showToast((jsonobject.toString(2)));
}
catch (JSONException ex)
{
}
}
}
LOG 显示强制关闭模拟器
05-16 19:19:35.354: E/AndroidRuntime(1015): FATAL EXCEPTION: main
05-16 19:19:35.354: E/AndroidRuntime(1015): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ela.spinner/com.ela.spinner.Parshingdata}: java.lang.NullPointerException
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.os.Handler.dispatchMessage(Handler.java:99)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.os.Looper.loop(Looper.java:137)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-16 19:19:35.354: E/AndroidRuntime(1015): at java.lang.reflect.Method.invokeNative(Native Method)
05-16 19:19:35.354: E/AndroidRuntime(1015): at java.lang.reflect.Method.invoke(Method.java:511)
05-16 19:19:35.354: E/AndroidRuntime(1015): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-16 19:19:35.354: E/AndroidRuntime(1015): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-16 19:19:35.354: E/AndroidRuntime(1015): at dalvik.system.NativeStart.main(Native Method)
05-16 19:19:35.354: E/AndroidRuntime(1015): Caused by: java.lang.NullPointerException
05-16 19:19:35.354: E/AndroidRuntime(1015): at com.ela.spinner.Parshingdata.onCreate(Parshingdata.java:24)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.Activity.performCreate(Activity.java:4465)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-16 19:19:35.354: E/AndroidRuntime(1015): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-16 19:19:35.354: E/AndroidRuntime(1015): ... 11 more 05-16 19:19:35.984: D/dalvikvm(1015): GC_CONCURRENT freed 301K, 5% free 9491K/9927K, paused 12ms+94ms
答案 0 :(得分:0)
你没有意图使用extas。所以当你打电话时
String sldept = getIntent().getExtras().getString("sldept");
它没有返回任何东西放入你的json对象。那么你就不能祝酒了。
答案 1 :(得分:0)
检查这些值,你没有从意图中获得一个值。
String sldept = getIntent().getExtras().getString("sldept");
String sldegree = getIntent().getExtras().getString("sldegree");
String slyear = getIntent().getExtras().getString("slyear");
String slsubjname = getIntent().getExtras().getString("slsubjname");
String slperiod = getIntent().getExtras().getString("slperiod");
String sldate = getIntent().getExtras().getString("sldate");
引起:java.lang.NullPointerException 05-16 19:19:35.354:E / AndroidRuntime(1015):at&gt; com.ela.spinner.Parshingdata.onCreate(Parshingdata.java:24)< /强>
这是发生错误的地方,所以这意味着该变量的值为null,那就是sldate,我想你是从intent.putExtra()得到的。因此,请从您调用此活动的位置检查actvity。也许你在intent.putExtra()中重新设置了这个varibale“sldate”或“slperiod”。
答案 2 :(得分:0)
@Chintan Raghwani
类的onclickgo()
方法, AndroidspinnerActivity
处于正确的轨道上。
如果您调用该方法,则不会为意图设置额外内容,因此当您调用getIntent().getExtras().getString("sldept");
时,它会抛出NPE
。
实际上getIntent().getExtras()
为空(你没有设置额外的东西!),你仍然试图从中获取一个字符串。
要绕过此问题,
Parshingdata
开始传递给onclickgo
类的意图:这种onclickgo()
方法应该是:
protected void onclickgo()
{
String sldeptdp = deptsp.getSelectedItem().toString();
String sldegreedp = degreesp.getSelectedItem().toString();
String slyeardp = yearsp.getSelectedItem().toString();
String subjnamee = subjname.getText().toString();
String sldatee = sldate.getText().toString();
String slperiodd = slperiod.getText().toString();
Intent intent = new Intent(this, Parshingdata.class);
intent.putExtra("sldept", sldeptdp);
intent.putExtra("sldegree", sldegreedp);
intent.putExtra("slyear", slyeardp);
intent.putExtra("slsubjname", subjnamee);
intent.putExtra("sldate", sldatee);
intent.putExtra("slperiod", slperiodd);
startActivity(intent);
startActivity(intent);
}
Parshingdata
的{{1}}方法中检查意图以获取额外内容,并仅在附加内容可用时执行操作。 onCreate
方法如下:
onCreate
为了最好,你应该实现两者。
答案 3 :(得分:-1)
尝试使用少量更改的代码
protected void onclickgo() {
Intent i = new Intent(AndroidspinnerActivity.this, Parshingdata.class);
startActivity(i);
}
在click事件中,上下文不会保留在您的Activity中,因此您必须在Intent时指定YourActivityName.this。