2015-01-17 107 views
1

我想要做的是首先在數據庫中插入一些值(請參閱insertvalues函數),然後從數據庫中將所有數據檢索到微調器(請參閱getvalues函數).i成功檢索數據從數據庫,我通過textboxes.Check當我設置這個數據到我的微調適配器和運行應用程序,我得到一個空spinner.i理解,我應該先寫行 My_spinner =(微調)findViewbyid( - )然後調用getvalues函數,但是當我嘗試移動此行(My_spinner =(微調)findViewbyid( - )在其他地方,我的應用程序不再工作,並說不幸的是該應用程序closed.i花了相當多的時間找出問題,但我不能,請幫助。使用數據庫中的數據填充微調器

packag e 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?" + "&regID="+ 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"); 
     } 



    } 

    //############################################################################################################### 
} 

//登錄貓編輯代碼的建議

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):致命例外:main 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):at com。 example.gcmclientapp.GcmServer $ 1.onItemSelected(GcmServer.java:123) 01-17 21:27:33.075:E/AndroidRuntime(1895):at 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):at android.os.Handler.handleCallback(Handler.java:730) 01-17 21:27:33.075:E/AndroidRuntime(1895):at android.os.Handler.dispatchMessage(Handler.java:92 ) 01-17 21:27:33.075:E/AndroidRuntime(1895):at android.os.Looper.loop(Looper.java:137) 01-17 21:27:33.075:E/AndroidRuntime(1895): at 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):在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(Zygo (原始方法)

回答

0

嘗試將值填充到微調器中,而不是任何內部的任何東西其他方法,但是在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對象作爲初級講座

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); 
+0

我試圖做如你所說,現在我的應用程序關閉,請檢查上述:( –

+0

嘗試logcat的返回一個列表,而不是一個String []的。 。因爲我認爲同樣的問題在這裏被問到http://stackoverflow.com/questions/21021565/android-spinner-adapter-setting-to-spinner –

+0

有一個....列表 list = new ArrayList ( ); ...在你的方法中,並將「name」值添加到列表中,而不是將它們拆分並構建一個數組,然後可以返回列表並從onCreate()中獲取並使用列表初始化適配器arr)將適配器設置爲Spinner。 –

0

儘量讓這段代碼工作,我不能調試在這個時刻之後填充值在onCreate()方法來微調。這是一個很高興幫助這個...

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?" + "&regID="+ 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; 

    } 

    //############################################################################################################### 
} 
+0

非常感謝你,我會試試這個,那真是太好了:) –

相關問題