我要做的是首先在数据库中插入一些值(参见insertvalues函数),然后从数据库中检索所有数据到spinner(参见getvalues函数).i成功检索数据库中的数据,我检查过textboxes.but当我将这些数据设置到我的微调器适配器并运行应用程序时,我得到一个空的spinner.i明白我应该先写这行 My_spinner =(spinner)findViewbyid( - )然后调用getvalues函数,但当我尝试移动此行(My_spinner =(spinner)findViewbyid( - )在其他地方时,我的应用程序不再工作并且不幸地说应用程序已经关闭。我花了很多时间来弄清楚问题,但我不能,请帮助。
package com.example.gcmclientapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
getTableValues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
@Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "®ID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public void getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
temp+=json_data.getString("name")+":";
}
//System.out.println(temp);
arr=temp.split(":");
tv.setText(arr[1]);
tv2.setText(arr[2]);
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
arr);
My_spinner.setAdapter(my_Adapter);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
}
//###############################################################################################################
}
//按建议编辑代码后记录cat
01-17 21:27:32.939:D / dalvikvm(1895):GC_FOR_ALLOC释放172K,3%免费9493K / 9692K,暂停3ms,总计3ms 01-17 21:27:33.019:W / EGL_genymotion(1895):eglSurfaceAttrib未实现 01-17 21:27:33.075:D / AndroidRuntime(1895):关闭VM 01-17 21:27:33.075:W / dalvikvm(1895):threadid = 1:线程退出未捕获异常(组= 0xa4be7648) 01-17 21:27:33.075:E / AndroidRuntime(1895):致命异常:主要 01-17 21:27:33.075:E / AndroidRuntime(1895):java.lang.IndexOutOfBoundsException:索引0无效,大小为0 01-17 21:27:33.075:E / AndroidRuntime(1895):at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 01-17 21:27:33.075:E / AndroidRuntime(1895):at java.util.ArrayList.get(ArrayList.java:308) 01-17 21:27:33.075:E / AndroidRuntime(1895):at com.example.gcmclientapp.GcmServer $ 1.onItemSelected(GcmServer.java:123) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.widget.AdapterView.fireOnSelected(AdapterView.java:892) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.widget.AdapterView.access $ 200(AdapterView.java:49) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.widget.AdapterView $ SelectionNotifier.run(AdapterView.java:860) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.os.Handler.handleCallback(Handler.java:730) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.os.Handler.dispatchMessage(Handler.java:92) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.os.Looper.loop(Looper.java:137) 01-17 21:27:33.075:E / AndroidRuntime(1895):在android.app.ActivityThread.main(ActivityThread.java:5103) 01-17 21:27:33.075:E / AndroidRuntime(1895):at java.lang.reflect.Method.invokeNative(Native Method) 01-17 21:27:33.075:E / AndroidRuntime(1895):at java.lang.reflect.Method.invoke(Method.java:525) 01-17 21:27:33.075:E / AndroidRuntime(1895):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737) 01-17 21:27:33.075:E / AndroidRuntime(1895):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 01-17 21:27:33.075:E / AndroidRuntime(1895):at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
尝试将值填充到Spinner中,而不是在任何其他方法中,而是在onCreate()方法中。尝试按以下方式更改您的计划:
将getTableValues()方法更改为:
public String[] getTableValues() {
从该方法中删除这些行:
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
并在方法结束处返回数组“arr”;
return arr;
然后在初始化My_spinner对象后,在onCreate()方法中将值填充到Spinner,如下所示
My_spinner = (Spinner) findViewById(R.id.spinner1);
arr = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
答案 1 :(得分:0)
尝试使此代码正常工作,因为我目前无法调试此代码。很高兴能帮到这个......
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
List<String> list = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
My_spinner.setAdapter(my_Adapter);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
@Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "®ID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public List<String> getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
List<String> list = new ArrayList<String>();
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
list.add(json_data.getString("name"));
}
//System.out.println(temp);
tv.setText(arr[1]);
tv2.setText(arr[2]);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
return list;
}
//###############################################################################################################
}