2016-05-28 181 views
1

嗨在每個機構我寫了一個程序,以獲取服務器的數據,並顯示與json 列表視圖中的數據,但是當我啓動應用程序,應用程序立即關閉。 我檢查了我的清單和它的好,idont知道我該怎麼做,請幫助我!關閉安卓程序立即在json運行應用程序

主要活動代碼:

package com.example.delta.travel; 

import android.app.ListActivity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.View; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.ListAdapter; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

public class MainActivity extends ListActivity { 

private ProgressDialog pd; 
JSONParser jParser=new JSONParser(); 
ArrayList<HashMap<String,String>> P; 
JSONArray s=null; 
private final String url="http://192.168.1.4/upload/travel.php"; 

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

    new travel().execute(); 

} 

class travel extends AsyncTask<String,String,String>{ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd=new ProgressDialog(MainActivity.this); 
     pd.setMessage("login"); 
     pd.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 

     List<NameValuePair> parms=new ArrayList<>(); 
     JSONObject json=jParser.makeHTTPRequest(url,"GET",parms); 
     try { 
      int t=json.getInt("t"); 
      if(t==1){ 
       s=json.getJSONArray("travel"); 
       for(int i=0;i<s.length();i++){ 
        JSONObject c=s.getJSONObject(i); 
        String companyname=c.getString("companyname"); 
        String cod=c.getString("cod"); 
        String bign=c.getString("bign"); 
        String stop=c.getString("stop"); 
        String date=c.getString("date"); 
        String time=c.getString("time"); 
        String price=c.getString("price"); 

        HashMap<String,String>map=new HashMap<String,String>(); 
        map.put("companyname",companyname); 
        map.put("cod",cod); 
        map.put("bign",bign); 
        map.put("stop",stop); 
        map.put("date",date); 
        map.put("time",time); 
        map.put("price",price); 

        P.add(map); 

       } 
      }else { 
       Toast.makeText(MainActivity.this,"No    DataFound",Toast.LENGTH_SHORT).show(); 
      } 


     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
     pd.dismiss(); 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list, 
         new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"}, 
         new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price}); 
       setListAdapter(adapter); 
      } 
     }); 

    } 
} 
} 

我JSONParser代碼:

package com.example.delta.travel; 

import android.net.http.HttpResponseCache; 
import android.util.Log; 

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.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.URL; 
import java.util.Date; 
import java.util.List; 

/** 
* Created by delta on 5/28/2016. 
*/ 
public class JSONParser { 

static InputStream is=null; 
static JSONObject jObj=null; 
static String json=""; 

// constructor 
public JSONParser(){ 

} 

// function get json from url 
// by making HTTP POST or GET method 
public JSONObject makeHTTPRequest(String url,String method, 
            List<NameValuePair> params){ 

    //making HTTP request 
    try{ 
     //check for request method 
     if(method=="POST"){ 
      // request method is POST 
      //defaultHTTPClient 
      DefaultHttpClient httpClient =new DefaultHttpClient(); 
      HttpPost httpPost=new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse=httpClient.execute(httpPost); 
      HttpEntity httpEntity=httpResponse.getEntity(); 
      is=httpEntity.getContent(); 
     }else if(method=="GET"){ 
      //request method is GET 
      DefaultHttpClient httpClient=new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params,"utf-8"); 
      url+="?"+paramString; 
      HttpGet httpGet=new HttpGet(url); 

      HttpResponse httpResponse=httpClient.execute(httpGet); 
      HttpEntity httpEntity=httpResponse.getEntity(); 
      is=httpEntity.getContent(); 



     } 

    }catch (UnsupportedEncodingException e){ 
     e.printStackTrace(); 
    }catch (ClientProtocolException e){ 
     e.printStackTrace(); 
    }catch (IOException e){ 
     e.printStackTrace(); 
    } 

    try{ 
     BufferedReader reader=new BufferedReader(new InputStreamReader(
       is,"iso-8859-1"),8); 
     StringBuilder sb=new StringBuilder(); 
     String line=null; 
     while ((line=reader.readLine())!=null){ 
      sb.append(line+"\n"); 
     } 
      is.close(); 
     json=sb.toString(); 
    }catch (Exception e){ 
     Log.e("Buffer Error","Error Converting result"+e.toString()); 
    } 

    //try parse the string to a JSON object 

    try{ 
     jObj=new JSONObject(json); 
    }catch (JSONException e){ 
     Log.e("JSON Parser","Error parsing data"+e.toString()); 
    } 
    //return JSON String 
    return jObj; 


} 


} 

和我travel.php代碼:

<?php 

$con=mysqli_connect("localhost","root","","travels"); 
mysqli_set_charset($con,"utf8"); 
$response=array(); 


$result=mysqli_query($con,"select * from travel"); 

if(mysqli_num_rows($result)>0){ 
while($row=mysqli_fetch_array($result)){ 
    $temp=array(); 
    $temp["companyname"]=$row["companyname"]; 
    $temp["cod"]=$row["cod"]; 
    $temp["bign"]=$row["bign"]; 
    $temp["stop"]=$row["stop"]; 
    $temp["date"]=$row["date"]; 
    $temp["time"]=$row["time"]; 
    $temp["price"]=$row["price"]; 

    $response["travel"]=array(); 

    array_push($response["travel"],$temp); 
    } 

$response["t"]=1; 
echo json_encode($response); 

} 
else{ 

$response["t"]=0; 
$response["message"]="Not Found"; 
echo json_encode($response); 

} 

?> 
+0

logcat內的任何東西? – Egor

+0

你在哪裏存儲從json解析器類返回的對象? –

回答

0

1)使用此代碼更改代碼在你JSONParser類。只使用這個小說。

public JSONObject makeHTTPRequest(String urlString, String method) { 

    if(method.equals("POST")){ 

     URL url = null; 
     try { 
      url = new URL(urlString); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Accept", "application/json"); 

      BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream()))); 
      String output; 
      StringBuilder sb = new StringBuilder(); 
      while ((output = br.readLine()) != null) { 
       sb.append(output); 
      } 
      conn.disconnect(); 
      json = sb.toString(); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    }else if(method.equals("GET")){ 
     URL url = null; 
     try { 
      url = new URL(urlString); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      conn.setRequestProperty("Accept", "application/json"); 

      BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream()))); 
      String output; 
      StringBuilder sb = new StringBuilder(); 
      while ((output = br.readLine()) != null) { 
       sb.append(output); 
      } 
      conn.disconnect(); 
      json = sb.toString(); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return jObj; 
} 

2)而在MainActivity必須添加P =新的ArrayList <>();在像這樣的onCreate()方法中。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    P = new ArrayList<>(); 
    new travel().execute(); 

} 

所有這一切都在我身邊工作。它肯定也適合你。

+0

我改變了我的AsyncTask函數代碼和JSONParser,但它的關閉應用程序當我啓動應用程序 – alireza

+0

你是否檢查了NullPointerException的形式?請給你的json字符串,你正在解析。 –

+0

我無法找到它在哪裏NullPointerException是來形式,但你可以下載我的文件在這個鏈接,並檢查http://s7.picofile.com/file/8253323134/Travel.zip.html – alireza

0

做一些改變,看看它的工作原理:

new travel().execute(url); 

您的AsyncTask:

class travel extends AsyncTask<String,Void,String>{ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd=new ProgressDialog(MainActivity.this); 
     pd.setMessage("login"); 
     pd.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 

     // List<NameValuePair> parms=new ArrayList<>(); 
for(urlString in params){ 
      JSONObject json=jParser.makeHTTPRequest(urlString,"GET"); 
} 
//rest is same 

在JSONParser類:

public class JSONParser { 

static InputStream is=null; 
static JSONObject jObj=null; 
static String json=""; 

// constructor 
public JSONParser(){ 

} 

// function get json from url 
// by making HTTP POST or GET method 
public JSONObject makeHTTPRequest(String url,String method){ 

    //making HTTP request 
    try{ 
     //check for request method 
     if(method=="POST"){ 
      // request method is POST 
      //defaultHTTPClient 
      DefaultHttpClient httpClient =new DefaultHttpClient(); 
      HttpPost httpPost=new HttpPost(url); 
      //httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse=httpClient.execute(httpPost); 
      HttpEntity httpEntity=httpResponse.getEntity(); 
      is=httpEntity.getContent(); 
     }else if(method=="GET"){ 
      //request method is GET 
      DefaultHttpClient httpClient=new DefaultHttpClient(); 
      ///String paramString = URLEncodedUtils.format(params,"utf-8"); 
      //url+="?"+paramString; 
      HttpGet httpGet=new HttpGet(url); 

      HttpResponse httpResponse=httpClient.execute(httpGet); 
      HttpEntity httpEntity=httpResponse.getEntity(); 
      is=httpEntity.getContent(); 



     } 
// Rest is same 
+0

我插入你的代碼,但在第二行:P = jp.makeHTTPRequest(url,「GET」,parms); 告訴我error.the錯誤說它的不兼容類型 – alireza

+0

我插入您的更新代碼,但仍然當我運行應用程序立即關閉 – alireza

+0

您可以粘貼您的LogCat報告? –