2013-04-26 2 views
0

после настройки классов ASyncTask для захвата необходимой мне информации. Теперь у меня есть еще одна проблема.Выбор элемента из Spinner в Android, а затем отображение объекта

По существу, вот мой сценарий:

После регулировки AsyncTask для ManifestItems, я создал класс AsyncTask для отправок, как партии является ManifestItem. По сути, то, что приложение должно делать, это отобразить детали консигнации (в новом действии), когда выбран ManifestItem в Spinner.

Я пробовал реализовать класс OnSelectedItemListener, но не попал в точку останова. На основании моего кода ниже, какой подход я могу принять? Благодарю.

package com.signonglass; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 


import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import org.json.*; 


import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.DialogInterface; 
import android.content.DialogInterface.OnCancelListener; 
import android.content.Intent; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Spinner; 
import android.widget.Toast; 

public class MainActivity extends Activity 
{ 
private final static String POD_URI = "http://192.168.0.105:8092/PodCore.svc"; 
private EditText evManifestCode; 
private Spinner list_job; 
private String jobName; 
private Button btnSearch; 
ArrayList<ManifestItemObj> jobList = new ArrayList<ManifestItemObj>(); 
ArrayList<ConsignmentItems> conItemList = new ArrayList<ConsignmentItems>(); 
Consignments con = new Consignments(); 
String consignment; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    evManifestCode = (EditText)findViewById(R.id.manifest); 
    list_job = (Spinner)findViewById(R.id.jobSpinner); 
    btnSearch = (Button)findViewById(R.id.btnSearch); 

} 

//ASyncTask to get ManifestItem from each manifest 
public class getManifestItems extends AsyncTask<String, Void, ArrayList<ManifestItemObj>> 
{ 
    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); 
    InputStream inputStream = null; 
    String theString = ""; 
    StringBuilder builder; 

    protected void onPreExecute() 
    { 
     progressDialog.setMessage("Loading manifests..."); 
     progressDialog.show(); 
     progressDialog.setOnCancelListener(new OnCancelListener() 
     { 
      public void onCancel(DialogInterface arg0) 
      { 
       getManifestItems.this.cancel(true); 
      } 
     }); 
    } 

    @Override 
    protected ArrayList<ManifestItemObj> doInBackground(String... params) 
    { 
     try 
     { 
      //http get request 
      HttpGet request = new HttpGet(POD_URI + "/getJobs/" + evManifestCode.getText().toString()); 
      //set the hedear to get the data in JSON format 
      request.setHeader("Accept", "application/json"); 
      request.setHeader("Content-type", "application/json"); 

      DefaultHttpClient client = new DefaultHttpClient(); 

      //get the response 
      HttpResponse response = client.execute(request); 
      HttpEntity entity = response.getEntity(); 

      //read content 
      InputStream is = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

      builder = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) { 
          builder.append(line); 
        } 
      is.close(); 
      theString = builder.toString(); 

      JSONObject jobsJSON = new JSONObject(theString); 
      JSONArray jobs = jobsJSON.getJSONArray("getJobsResult"); 

      for(int i = 1; i < jobs.length(); i++) 
      { 
       JSONObject mit = jobs.getJSONObject(i); 
       ManifestItemObj mi = new ManifestItemObj(); 
       mi.ManifestItemID = mit.getInt("ManifestItemID"); 
       mi.JobType = mit.getString("JobType"); 
       mi.FKID = mit.getInt("FKID"); 
       jobList.add(mi); 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return jobList; 
    } 

    protected void onPostExecute(ArrayList<ManifestItemObj> mio) 
    { 
     ManifestItemAdapter mia = new ManifestItemAdapter(MainActivity.this, android.R.layout.simple_spinner_item, jobList); 
     this.progressDialog.dismiss(); 
     list_job.setAdapter(mia); 

    } 

    /*@Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
    { 
     // TODO Auto-generated method stub 
     ManifestItemObj selectedJob = jobList.get(position); 
     jobName = selectedJob.getJobType() + Integer.toString(selectedJob.getConsignmentID()); 
     consignment = jobName; 

     if(position != 0) 
     { 
      showToast(jobName + " " + "was selected!"); 
      new getConsignment().execute(jobName); 
     } 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) 
    { 
     // TODO Auto-generated method stub 

    }*/ 
} 

public class getConsignment extends AsyncTask<String, Void, Consignments> 
{ 
    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); 
    InputStream inputStream = null; 
    String theString = ""; 
    StringBuilder builder; 

    protected void onPreExecute() 
    { 
     progressDialog.setMessage("Loading consignments..."); 
     progressDialog.show(); 
     progressDialog.setOnCancelListener(new OnCancelListener() 
     { 
      public void onCancel(DialogInterface arg0) 
      { 
       getConsignment.this.cancel(true); 
      } 
     }); 
    } 

    @Override 
    protected Consignments doInBackground(String... arg0) 
    { 
     try 
     { 
      DefaultHttpClient client = new DefaultHttpClient(); 
      String theString = new String(""); 
      //http get request 
      HttpGet request = new HttpGet(POD_URI + "/getJobDetails/" + consignment); 
      //set the hedear to get the data in JSON format 
      request.setHeader("Accept", "application/json"); 
      request.setHeader("Content-type", "application/json"); 

      //get the response 
      HttpResponse response = client.execute(request); 
      HttpEntity entity = response.getEntity(); 
      InputStream is = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

      StringBuilder builder = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) 
      { 
       builder.append(line); 
      } 
      is.close(); 

      theString = builder.toString(); 

      JSONObject conJSON = new JSONObject(theString); 
      JSONArray cons = conJSON.getJSONArray("getJobDetailsResult"); 

      for(int i = 0; i < cons.length(); i++) 
      { 
       JSONObject cObj = cons.getJSONObject(i); 
       con.ConsignmentID = cObj.getInt("ConsignmentID"); 
       con.ConsignmentCreationDate = cObj.getString("ConsignmentCreationDate"); 
       con.ConsignmentCustRef = cObj.getString("ConsignmentCustRef"); 
       con.OrderNo = cObj.getString("OrderNo"); 
       con.ConsignmentActive = cObj.getBoolean("ConsignmentActive"); 
       con.JobType = cObj.getString("JobType"); 

       //Client object 
       JSONObject clObj = cObj.getJSONObject("Client"); 
       Clients cl = new Clients(); 
       cl.ClientId = clObj.getInt("ClientID"); 
       cl.ClientName = clObj.getString("ClientName"); 
       con.Clients = cl; 

       //ShipTo object 
       JSONObject stObj = cObj.getJSONObject("ShipTo"); 
       ShipTo sto = new ShipTo(); 
       sto.ShipToId = stObj.getInt("ShipToId"); 
       sto.ShipToName = stObj.getString("ShipToName"); 
       sto.ShipToAddress1 = stObj.getString("ShipToAddress1"); 
       sto.ShipToAddress2 = stObj.getString("ShipToAddress2"); 
       sto.ShipToCity = stObj.getString("ShipToCity"); 
       sto.ShipToPostcode = stObj.getString("ShipToPCode"); 
       sto.ShipToState = stObj.getString("ShipToState"); 
       con.ShipTo = sto; 

       //FreightZone object 
       JSONObject fzObj = cObj.getJSONObject("FreightZone"); 
       FreightZones fz = new FreightZones(); 
       fz.FreightZoneID = fzObj.getInt("FreightZoneId"); 
       fz.FreightZone = fzObj.getString("FreightZone"); 
       con.FreightZone = fz; 

       JSONArray conItems = cObj.getJSONArray("ConsignmentItems"); 

       for(int m = 0; m < conItems.length(); m++) 
       { 
        JSONObject cit = conItems.getJSONObject(m); 
        ConsignmentItems ci = new ConsignmentItems(); 
        ci.ConsignmentItemID = cit.getInt("ConsignmentItemsID"); 
        ci.Quantity = cit.getInt("QTY"); 

        //get Product from ConsignmentItems 
        JSONObject pro = cit.getJSONObject("Products"); 
        Products prod = new Products(); 
        prod.ProductId = pro.getInt("ProductID"); 
        prod.ProductModel = pro.getString("ProductModel"); 
        prod.ItemsPerCarton = pro.getInt("PerCarton"); 
        prod.ProductDescription = pro.getString("Description"); 
        prod.Height = (float) pro.getDouble("Height"); 
        prod.Length = (float) pro.getDouble("Length"); 
        prod.Width = (float) pro.getDouble("Width"); 
        prod.Cubic = (float) pro.getDouble("Cubic"); 
        ci.Product = prod; 
        conItemList.add(ci); 
        con.ConsignmentItems = conItemList; 
       } 
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return con; 
    } 

    protected void onPostExecute(Consignments conselect) 
    { 
     ShowItemsOfManifest(con); 
    } 

} 

public void ShowItemsOfManifest(Consignments consignments) 
{ 
    Bundle bundle = new Bundle(); 
    Intent newIntent = new Intent(this.getApplicationContext(), ConActivity.class); 
    newIntent.putExtras(bundle); 
    newIntent.putExtra("Consignment", consignments); 

    this.startActivity(newIntent); 

} 

public void btnSearchClick(View view) 
{ 
    new getManifestItems().execute(); 
} 

}

ответ

1

Вам нужно добавить слушатель в Spinner. Что-то вроде

list_job = (Spinner)findViewById(R.id.jobSpinner); 
btnSearch = (Button)findViewById(R.id.btnSearch); 

list_job.setOnItemSelectedListener(this); // add the listener here 

и реализации слушателя

public class MainActivity extends Activity implements OnItemSelectedListener{ 
+0

пробовал. Это работает потрясающе. Спасибо за кучи за это. :) – cmnunis

+0

Без проблем, рад, что смогу помочь – codeMagic

+0

Привет @codeMagic, возможно ли это сделать? 'public class getManifestItems extends AsyncTask > реализует OnItemSelectedListener?' – cmnunis

Смежные вопросы