2017-01-23 23 views
0

我遇到了android studio中parseData()java函數的問題。我需要在一項活動中多次使用它。它首次加載時,會從URL中獲取信息並將信息顯示在列表中。這部分工作grea,但現在我需要能夠點擊每個列表並運行每個單元的parseData,每個項目都有一個我需要觸發的唯一URL,該URL告訴數據庫將該項目的數量減少一個。當我嘗試運行parseData()函數,在文件中傳遞parseData函數並傳遞它唯一的url時,它丟失了cookie或未通過授權(登錄會話),因此應用程序失敗,並顯示以下錯誤。 URL的日誌返回302重定向,我認爲登錄會話信息丟失或沒有正確傳遞給url,它會嘗試發回登錄活動,然後導致「HttpResponse responseNew = LoginActivity.client.execute(httppost) ;」使用parsedata解析XML()在Android會話中失去登錄

任何幫助將是偉大的。

活動代碼

package com.mike_scanncer_example.mike_scanner; 



import java.io.IOException; 

import java.net.URL; 
import java.lang.Object; 



import android.app.Activity; 
import java.io.BufferedInputStream; 

import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLEncoder; 
import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import java.net.HttpURLConnection; 
import android.os.Bundle; 
import android.os.Handler; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.BaseAdapter; 
import android.widget.ImageButton; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.kosalgeek.genasync12.AsyncResponse; 
import com.kosalgeek.genasync12.PostResponseAsyncTask; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpPost; 
import org.xml.sax.Attributes; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 
import org.xml.sax.XMLReader; 
import org.xml.sax.helpers.DefaultHandler; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.Vector; 

import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 

public class Search_Result extends Activity { 
    private Handler mHandler=new Handler(); 
    ProgressDialog dialog; 
    String ticket_no=""; 
    String cname=""; 
    String order_no=""; 
    String card_no=""; 
    String url=""; 
    Vector<Vector<String>> data =null; 
    String [] number=null; 
    String [] checkedin =null; 
    String [] type=null; 
    String auth=""; 
    String msg=""; 
    String status=""; 
    String reply=""; 
     String mssg=""; 
     String c_time=""; 
     boolean f=true; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.ticket_check); 

     ImageButton back = (ImageButton) findViewById(R.id.back_search); 
       back.setOnClickListener(new OnClickListener() { 


        public void onClick(View v) { 

        Search_Result.this.finish(); 
        } 
       }); 


     Bundle extra = getIntent().getExtras(); 
     Log.v("bundle", String.valueOf(extra)); 

     url=extra.getString("url"); 
     Log.v("LOG", url); 

     data = new Vector<Vector<String>>(); 


     final ListView l1 =(ListView)findViewById(R.id.ticket_list); 
     dialog = ProgressDialog.show(Search_Result.this,"", 
        "Loading...", true); 
     l1.setDivider(null); 

     final Thread t =new Thread(new Runnable() { 


      public void run() { 
       parseData(); 

      } 
     }); 
     t.start(); 
     Thread t1 =new Thread(new Runnable() { 


      public void run() { 
       // TODO Auto-generated method stub 

       try { 
         t.join(); 
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

        mHandler.post(new Runnable() { 


         public void run() { 
         dialog.cancel(); 


          if(auth.equals("success")) 
          { 
           Log.v("login-info",auth); 
           number=new String[data.size()]; 
           checkedin=new String[data.size()]; 
           type=new String[data.size()]; 
           for(int j=0; j<data.size(); j++) 
           { 
           number[j]=data.get(j).get(0); 
           checkedin[j]=data.get(j).get(1); 
           type[j]=data.get(j).get(2); 
           } 
          } 
          else 
          { 


           if(msg.equals("Please Login First")) 
           { 
            Intent intent = new Intent(Search_Result.this, LoginActivity.class); 
            startActivity(intent); 
            Toast.makeText(Search_Result.this, msg, Toast.LENGTH_SHORT).show(); 
           } 
           else 
           { 
            //Toast.makeText(Search_Result.this, msg, Toast.LENGTH_SHORT).show(); 

            AlertDialog.Builder dialog2 = new AlertDialog.Builder(Search_Result.this); 
            dialog2.setMessage("Sorry!\nRecord not found."); 
            dialog2 .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
              public void onClick(final DialogInterface dialog, final int id) 
              { 
               finish(); 
              } 
             }); 
            dialog2.show(); 
           } 


          } 


         l1.setAdapter(new EfficientAdapter(getApplicationContext())); 
         l1.setOnItemClickListener(new OnItemClickListener() { 


          public void onItemClick(AdapterView<?> arg0, 
            View arg1, int position, long id) { 


          } 


         }); 


         } 
        }); 

      } 
     }); 

     t1.start(); 

    } 


    private void parseData() 
    { 
     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp = null; 
     try { 
      sp = spf.newSAXParser(); 
     } catch (ParserConfigurationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Get the XMLReader of the SAXParser we created. 
     XMLReader xr = null; 
     try { 
      xr = sp.getXMLReader(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     // Create a new ContentHandler and apply it to the XML-Reader 
     MyExampleHandlerGarbageDepot myExampleHandler = new MyExampleHandlerGarbageDepot(); 
     xr.setContentHandler(myExampleHandler); 

     // Parse the xml-data from our URL. 
     try { 

     String urlToHit = url; 

     URL url=new URL(urlToHit); 

     HttpPost httppost = new HttpPost(url.toString()); 

     HttpResponse response = LoginActivity.client.execute(httppost); 

     // Get hold of the response entity 
      HttpEntity entity = response.getEntity(); 

      InputStream instream = null; 

      if (entity != null) 
      { 
       instream = entity.getContent(); 
      } 

      xr.parse(new InputSource(instream)); 



      //HttpPost http=new HttpPost(url.toString()); 

      //HttpResponse res=client.execute(http); 
     // Log.v("response code",""+res); 

     // xr.parse(new InputSource(url.openStream())); 


     } catch (MalformedURLException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 


    class MyExampleHandlerGarbageDepot extends DefaultHandler 
    { 



      private Vector<String> singleItem1=null; 

    // private boolean Rss = false;  
     //private int i=0; 
     // =========================================================== 
     // Methods 
     // =========================================================== 
     @Override 
     public void startDocument() throws SAXException { 
     //this.myParsedExampleDataSet = new ParsedExampleDataSet(); 

     } 

     @Override 
     public void endDocument() throws SAXException { 
     // Nothing to do 

     } 

     @Override 
     public void startElement(String namespaceURI, String localName, 
       String qName, Attributes atts) throws SAXException { 


      if(localName.equals("Reply")) 
      { 

       auth=atts.getValue("replyCode"); 
       msg=atts.getValue("msg"); 
       Log.v("@#@#@",auth); 

      } 
      else if(localName.equals("Tickets")){ 



      } 
      else if(localName.equals("Ticket")) 
      { 

        singleItem1=new Vector<String>(); 
       singleItem1.add(atts.getValue("number")); 
       singleItem1.add(atts.getValue("checkedin")); 
       singleItem1.add(atts.getValue("type")); 

      } 


      } 



     /** Gets be called on closing tags like: 
     * </tag> */ 
     @Override 
     public void endElement(String namespaceURI, String localName, String qName) 
       throws SAXException { 

      if(localName.equals("Tickets")) 
      { 

      } 
      else if(localName.equals("Ticket")) 
      { 
       data.add(singleItem1); 
      } 

     } 

    /** Gets be called on the following structure: 
    * <tag>characters</tag> */ 
    @Override 
    public void characters(char ch[], int start, int length) { 


    } 
    } 


    private void parseNewData(String new_url) 
    { 
     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp = null; 
     try { 
      sp = spf.newSAXParser(); 
     } catch (ParserConfigurationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Get the XMLReader of the SAXParser we created. 
     XMLReader xr = null; 
     try { 
      xr = sp.getXMLReader(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     // Create a new ContentHandler and apply it to the XML-Reader 
     MyHandlerGarbageDepot myExampleHandler = new MyHandlerGarbageDepot(); 
     xr.setContentHandler(myExampleHandler); 

     // Parse the xml-data from our URL. 
     try { 

     String urlToHit = new_url; 
     Log.v("test123", new_url); 
     URL url=new URL(urlToHit); 

     HttpPost httppost = new HttpPost(url.toString()); 

     HttpResponse responseNew = LoginActivity.client.execute(httppost); 

     // Get hold of the response entity 
      HttpEntity entity = responseNew.getEntity(); 

      InputStream instream = null; 

      if (entity != null) 
      { 
       instream = entity.getContent(); 
      } 

      xr.parse(new InputSource(instream)); 



      //HttpPost http=new HttpPost(url.toString()); 

      //HttpResponse res=client.execute(http); 
     // Log.v("response code",""+res); 

     // xr.parse(new InputSource(url.openStream())); 


     } catch (MalformedURLException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      Log.d("Net Disconnected", "NetDisconeeted"); 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 


    class MyHandlerGarbageDepot extends DefaultHandler 
    { 



     private boolean checkin =false; 
    // private boolean Rss = false;  
     //private int i=0; 
     // =========================================================== 
     // Methods 
     // =========================================================== 
     @Override 
     public void startDocument() throws SAXException { 
     //this.myParsedExampleDataSet = new ParsedExampleDataSet(); 

     } 

     @Override 
     public void endDocument() throws SAXException { 
     // Nothing to do 

     } 

     @Override 
     public void startElement(String namespaceURI, String localName, 
       String qName, Attributes atts) throws SAXException { 


      if(localName.equals("Reply")) 
      { 

       reply=atts.getValue("replyCode"); 
       mssg=atts.getValue("msg"); 
       c_time=atts.getValue("time"); 
       Log.v("@#@#@",auth); 

      } 

       if(localName.equals("Checkedin")) 
        { 
       checkin = true; 

       } 


     } 




     /** Gets be called on closing tags like: 
     * </tag> */ 
     @Override 
     public void endElement(String namespaceURI, String localName, String qName) 
       throws SAXException { 

      if(localName.equals("Checkedin")) 
      { 
      checkin=false; 
      } 


     } 

    /** Gets be called on the following structure: 
    * <tag>characters</tag> */ 
    @Override 
    public void characters(char ch[], int start, int length) { 

      if(checkin) 
      { 
       status = new String(ch,start,length); 
      } 

    } 
    } 




    private class EfficientAdapter extends BaseAdapter { 
     private LayoutInflater mInflater; 

     public EfficientAdapter(Context context) { 
     mInflater = LayoutInflater.from(context); 

     } 

     public int getCount() { 
     return data.size(); 
     } 

     public Object getItem(int position) { 
     return position; 
     } 

     public long getItemId(int position) { 
     return position; 
     } 

     public View getView(final int position, View convertView, ViewGroup parent) { 
     final ViewHolder holder; 


     if (convertView == null) { 
     convertView = mInflater.inflate(R.layout.ticket_list, null); 
     holder = new ViewHolder(); 

     holder.text = (TextView) convertView.findViewById(R.id.ticket_num); 
     holder.text1 = (TextView) convertView.findViewById(R.id.ticket_type); 
     holder.check_img = (ImageButton) convertView.findViewById(R.id.ticket_status); 

     convertView.setTag(holder); 
     } else { 
     holder = (ViewHolder) convertView.getTag(); 
     } 
      holder.text.setText(data.get(position).get(0)); 
      holder.text1.setText(data.get(position).get(2)); 

      if(data.get(position).get(1).equals("0")){ 
       holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_inbut)); 
      } 
      else{ 
       holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.checked_in_but)); 
      } 

      holder.check_img.setOnClickListener(new OnClickListener() { 


       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 

        if(data.get(position).get(1).equals("0")){ 
         //Toast.makeText(Search_Result.this,"check",Toast.LENGTH_SHORT).show(); 
         url=Config.baseUrl+"checkin/"+Config.eventId+"/"+data.get(position).get(0); 

         parseNewData(url); 



         if(reply.equals("success")) 
          { 

             if(status.equals("0")) 
             { 
              holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_inbut)); 
             } 
             else 
             { 
              holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_back)); 
              Toast.makeText(Search_Result.this, "Check out", Toast.LENGTH_SHORT).show(); 

             } 
          } 
          else 
          { 


            if(mssg.equals("Please Login First")) 
            { 

             Intent intent = new Intent(Search_Result.this, LoginActivity.class); 
             startActivity(intent); 
             Toast.makeText(Search_Result.this, mssg, Toast.LENGTH_SHORT).show();  


           }    
          } 


        } 
        else{ 

         url=Config.baseUrl+"checkinInfo/"+Config.eventId+"/"+data.get(position).get(0); 
         //parseNewData(url); 
         Log.v("LOG", url); 

         AlertDialog.Builder builder = new AlertDialog.Builder(Search_Result.this); 
         AlertDialog.Builder builder1 = builder.setMessage("Ticket is already checked in") 
           .setCancelable(false) 
           .setPositiveButton("view details", new DialogInterface.OnClickListener() { 

            public void onClick(DialogInterface dialog, int id) { 
             String contents = data.get(position).get(0); 
             Intent intent = new Intent(Search_Result.this, Ticket_detail.class); 
             intent.putExtra("ticket_no", contents); 
             intent.putExtra("event_id", Config.eventId); 
             startActivity(intent); 
            } 
           }) 
           .setNegativeButton("close", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int id) { 
             dialog.cancel(); 
            } 
           }); 
         builder.show(); 


        } 

       } 
      }); 

         return convertView; 

    } 
    } 

static class ViewHolder { 
    TextView text; 
    TextView text1; 
    ImageButton check_img; 
    } 


} 

輸出錯誤日誌

> E/AndroidRuntime: FATAL EXCEPTION: main 
>     Process: com.mike_scanncer_example.mike_scanner, PID: 2516 
>     android.os.NetworkOnMainThreadException 
>      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) 
>      at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:300) 
>      at com.android.org.conscrypt.OpenSSLSocketImpl.shutdownAndFreeSslNative(OpenSSLSocketImpl.java:1194) 
>      at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1189) 
>      at org.apache.http.impl.SocketHttpClientConnection.shutdown(SocketHttpClientConnection.java:188) 
>      at org.apache.http.impl.conn.DefaultClientConnection.shutdown(DefaultClientConnection.java:155) 
>      at org.apache.http.impl.conn.SingleClientConnManager$PoolEntry.shutdown(SingleClientConnManager.java:445) 
>      at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:249) 
>      at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:195) 
>      at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:332) 
>      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560) 
>      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492) 
>      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470) 
>      at com.mike_scanncer_example.mike_scanner.Search_Result.parseNewData(Search_Result.java:403) 
>      at com.mike_scanncer_example.mike_scanner.Search_Result.access$200(Search_Result.java:63) 
>      at com.mike_scanncer_example.mike_scanner.Search_Result$EfficientAdapter$1.onClick(Search_Result.java:579) 
>      at android.view.View.performClick(View.java:5637) 
>      at android.view.View$PerformClick.run(View.java:22429) 
>      at android.os.Handler.handleCallback(Handler.java:751) 
>      at android.os.Handler.dispatchMessage(Handler.java:95) 
>      at android.os.Looper.loop(Looper.java:154) 
>      at android.app.ActivityThread.main(ActivityThread.java:6119) 
>      at java.lang.reflect.Method.invoke(Native Method) 
>      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
>      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
> Disconnected from the target VM, address: 'localhost:8648', transport: 
> 'socket' 

回答

1

你的異常錯誤輸出表明

NetworkOnMainThreadException

它看起來對我來說,它在你的parseData例外發生在這裏:

HttpPost httppost = new HttpPost(url.toString()); 

    HttpResponse response = LoginActivity.client.execute(httppost); 

您不能在主線程網絡調用。在你的onCreate調用中,而不是Runnables,我會看看使用AsyncTask。它會清理onCreate方法中的代碼,並在調用完成時爲您提供覆蓋(protected void onPostExecute)

+0

這是正確的答案。 –