2016-10-22 7 views
1

にJSONArrayを表示する方法をアンドロイド - ..私はJSON <a href="http://www.zxccvvv.cuccfree.com/send_data.php" rel="nofollow">here</a>を作成するためにPHPスクリプトを設定しているが、私はJSONArrayを表示しようとすると、私は私のAndroidのモニターに、このようないくつかのエラーを得たのTextView

値(HTML)(ボディ)(java.lang.String型のスクリプトがJSONArray

に変換することができない誰かがそれを修正する方法を教えてください?

MainActivity.java私はhere

任意のアイデアからの参照コードを持っHttpHandler.java

package flix.yudi.okhttp1; 

import android.util.Log; 

import java.io.BufferedInputStream; 
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.ProtocolException; 
import java.net.URL; 

public class HttpHandler { 

    private static final String TAG = HttpHandler.class.getSimpleName(); 

    public HttpHandler() { 
    } 

    public String makeServiceCall(String reqUrl) { 
     String response = null; 
     try { 
      URL url = new URL(reqUrl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      // read the response 
      InputStream in = new BufferedInputStream(conn.getInputStream()); 
      response = convertStreamToString(in); 
     } catch (MalformedURLException e) { 
      Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
     } catch (ProtocolException e) { 
      Log.e(TAG, "ProtocolException: " + e.getMessage()); 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.getMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
     return response; 
    } 

    private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append('\n'); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 
package flix.yudi.okhttp1; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

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

public class MainActivity extends AppCompatActivity { 

    private String TAG = MainActivity.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 

    // URL to get contacts JSON 
    private static String url = "http://zxccvvv.cuccfree.com/send_data.php"; 

    ArrayList<HashMap<String, String>> contactList; 

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

     contactList = new ArrayList<>(); 

     lv = (ListView) findViewById(R.id.list); 

     new GetContacts().execute(); 
    } 

    /** 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url); 

      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONArray jsonObj = new JSONArray(jsonStr); 

        // Getting JSON Array node 
        JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); 

        // looping through All Contacts 
        for (int i = 0; i < pertanyaan.length(); i++) { 
         JSONObject c = pertanyaan.getJSONObject(i); 

         String id = c.getString("id"); 
         String ask = c.getString("ask"); 

         // tmp hash map for single contact 
         HashMap<String, String> pertanyaans = new HashMap<>(); 

         // adding each child node to HashMap key => value 
         pertanyaans.put("id", id); 
         pertanyaans.put("ask", ask); 

         // adding contact to contact list 
         contactList.add(pertanyaans); 
        } 
       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        MainActivity.this, contactList, 
        R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask}); 

      lv.setAdapter(adapter); 
     } 

    } 
} 

/別の参照方法は、解決するには?

EDIT

send_data.php 
<?php 
include 'dbconfig.php'; 
$conn = new mysqli($servername, $username, $password, $dbname); 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
$sql = "SELECT id, ask FROM pertanyaan"; 
$result = $conn->query($sql); 
if ($result->num_rows > 0) { 
    // output data of each row 
    while($row[] = $result->fetch_assoc()) { 
     $json = json_encode($row); 

    } 
} else { 
    echo "0 results"; 
} 
mysql_close($dbname); 
echo $json; 
?> 

答えて

2

あなたはJSONをフェッチしている間にこれだけの配列を通じトラバースで、実際の文字列値をあるキーpertanyaanjsonObjからjsonarrayを取得しようとしていますインデックスを使用するオブジェクト

JSONArray jsonObj = new JSONArray(jsonStr); 

        // Getting JSON Array node 
        //JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); problem 

        // looping through All Contacts 
        for (int i = 0; i < jsonObj.length(); i++) { 
        JSONObject c = jsonObj.getJSONObject(i); 

        String id = c.getString("id"); 
        String ask = c.getString("ask"); 

        HashMap<String, String> pertanyaans = new HashMap<>(); 

        pertanyaans.put("id", id); 
        pertanyaans.put("ask", ask); 

        contactList.add(pertanyaans); 
       } 

注:キーpertanyaanとは、このようなjasonarrayはあなたの応答

PHPのアップデートではありません。応答を受信しながら、あなたのサービスによる使用

echo json_encode($json); 
+0

は私が私の> JSONArray pertanyaan = jsonObj.getJSONArray( "pertanyaan")を削除しなければならないです。卿? – Flix

+0

@Flixええ、私の投稿に表示されているように 'pertanyaan'の場所に' jsonObj'を使用してください。 –

+0

私はJSONを作成するPHPコードを宣言する必要がありますか? – Flix

1

は、あなたがJSONArray

this [{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{"id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask":"pertanyaan ke 5"}]のようなあなたを単に取得しますこの応答を保存する必要があります JSONArray

JSONArray jsonArray = new JSONArray(); 
jsonArray = (response); 

あなたはjsonArrayで応答を得て、その値からオプトアウトすることができます。ここ は、サンプル・コード・スニペット

for (int i = 0; i < jsonArray.length(); i++) { 
     try { 
      String id = jsonArray.getJSONObject(i).getString("id"); 
      String ask = jsonArray.getJSONObject(i).getString("ask"); 
      Log.i("TAG", "id "+ id + " ask "+ ask); 
      //you can set value to text view here 
      textview.settext(id + " "+ ask); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 
+0

私は上記のurコードを試しましたが、 "応答"と入力するとエラーが発生し、レスポンスと呼ばれる新しいクラスを作成するよう指示します。 – Flix

+0

レスポンスを正しいレスポンスに置き換える必要があります –

関連する問題

 関連する問題