【发布时间】:2015-01-18 01:04:33
【问题描述】:
我要做的是首先在数据库中插入一些值(请参阅 insertvalues 函数),然后将数据库中的所有数据检索到微调器中(请参阅 getvalues 函数)。我成功地从我检查过的数据库中检索数据文本框。但是当我将此数据设置到我的微调器适配器并运行应用程序时,我得到一个空微调器。我知道我应该先写一行 My_spinner=(spinner)findViewbyid(--) 然后调用 getvalues 函数,但是当我尝试将此行移动时已关闭。我花了很多时间来解决问题,但我无法解决问题,请帮忙。
包 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: 线程以未捕获的异常退出 (group=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): 在 java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 01-17 21:27:33.075: E/AndroidRuntime(1895): 在 java.util.ArrayList.get(ArrayList.java:308) 01-17 21:27:33.075: E/AndroidRuntime(1895): 在 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): 在 java.lang.reflect.Method.invokeNative(Native Method) 01-17 21:27:33.075: E/AndroidRuntime(1895): 在 java.lang.reflect.Method.invoke(Method.java:525) 01-17 21:27:33.075: E/AndroidRuntime(1895): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 01-17 21:27:33.075: E/AndroidRuntime(1895): 在 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)
【问题讨论】: