2015-04-22 2 views
2

Я работаю над java-приложением, которое использует удаленную базу данных mysql для извлечения данных. У меня есть webserivce между приложением и базой данных, которая выводит данные в формате JSON.Проблемы с Android JSON

Я пытаюсь разобрать файл JSON, не получая никаких ошибок, но экран на APP пуст.

Я искал часы для различных методов, чтобы сделать это, я разобрал все ошибки, с которыми столкнулся, но я не знаю, как идти отсюда.

MenuActivity.java

import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.StrictMode; 
import android.support.v4.app.NavUtils; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.webkit.WebView; 
import android.widget.TextView; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

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



public class MenuActivity extends ActionBarActivity { 

    // The JSON REST Service 
    static String URL = "http://alirajrestaurant.com/app/get.php"; 

    // Will hold the values I pull from the JSON 
    static String itmName = ""; 
    static String itmDesc = ""; 
    static String itemPrice = ""; 

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

     //Add Toolbar 
     Toolbar toolbar=(Toolbar) findViewById(R.id.app_bar); 
     setSupportActionBar(toolbar); 



     //Setup Home Navigation Button 
     getSupportActionBar().setHomeButtonEnabled(true); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); //display UP Icon 
     new MyAsyncTask().execute(); 





    } 



    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_menu, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     //Navigate Right Button on Toolbar to get to next Activity 
     if(id==R.id.navigate_right) 
     { 
      startActivity(new Intent(this,ResActivity.class)); 
     } 

     //What to do if Home Button is clicked 
     if(id==android.R.id.home) 
     { 
      NavUtils.shouldUpRecreateTask(this, new Intent(this,MainActivity.class)); 
     } 

     return super.onOptionsItemSelected(item); 
    } 


    private class MyAsyncTask extends AsyncTask<String, String, String> { 

     protected String doInBackground(String... arg0) { 

      // HTTP Client that supports streaming uploads and downloads 
      DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 

      // Define that I want to use the POST method to grab data from 
      // the provided URL 
      HttpPost httppost = new HttpPost(URL); 

      // Web service used is defined 
      httppost.setHeader("Content-type", "application/json"); 

      // Used to read data from the URL 
      InputStream inputStream = null; 

      // Will hold the whole all the data gathered from the URL 
      String result = null; 

      try { 

       // Get a response if any from the web service 
       HttpResponse response = httpclient.execute(httppost); 

       // The content from the requested URL along with headers, etc. 
       HttpEntity entity = response.getEntity(); 

       // Get the main content from the URL 
       inputStream = entity.getContent(); 

       // JSON is UTF-8 by default 
       // BufferedReader reads data from the InputStream until the Buffer is full 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 

       // Will store the data 
       StringBuilder theStringBuilder = new StringBuilder(); 

       String line = null; 

       // Read in the data from the Buffer untilnothing is left 
       while ((line = reader.readLine()) != null) 
       { 

        // Add data from the buffer to the StringBuilder 
        theStringBuilder.append(line + "\n"); 
       } 

       // Store the complete data in result 
       result = theStringBuilder.toString(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      finally { 

       // Close the InputStream when you're done with it 
       try{if(inputStream != null)inputStream.close();} 
       catch(Exception e){} 
      } 

      // Holds Key Value pairs from a JSON source 
      JSONObject jsonObject; 
      try { 


       JSONObject jObject = new JSONObject(result.substring(3)); 


       // GET ARRAY DATA 
       JSONArray jArray = new JSONArray(); 

       JSONObject oneObject = jArray.getJSONObject(' '); 
       // Pulling items from the array 
       itmName = oneObject.getString("name"); 
       itmDesc =oneObject.getString("desc"); 
       itemPrice = oneObject.getString("price"); 




      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return result; 

     } 

     protected void onPostExecute(String result){ 

      // Gain access so I can change the TextViews 
      TextView line1 = (TextView)findViewById(R.id.name_result); 
      TextView line2 = (TextView)findViewById(R.id.desc_result); 
      TextView line3 = (TextView)findViewById(R.id.price_result); 

      // Change the values for all the TextViews 
      line1.setText(itmName); 

      line2.setText(itmDesc); 

      line3.setText("£: " + itemPrice); 

     } 

    } 



    } 

JSONParse.java

public class JSONParse { 

public JSONArray GetAllItems() 
{ 
    // URL for getting all customers 


    String url = "http://alirajrestaurant.com/app/get.php"; 

    // Get HttpResponse Object from url. 
    // Get HttpEntity from Http Response Object 

    HttpEntity httpEntity = null; 

    try 
    { 

     DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient 
     HttpGet httpGet = new HttpGet(url); 

     HttpResponse httpResponse = httpClient.execute(httpGet); 

     httpEntity = httpResponse.getEntity(); 



    } catch (ClientProtocolException e) { 

     // Signals error in http protocol 
     e.printStackTrace(); 

     //Log Errors Here 



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


    // Convert HttpEntity into JSON Array 
    JSONArray jsonArray = null; 

    if (httpEntity != null) { 
     try { 
      String entityResponse = EntityUtils.toString(httpEntity); 

      Log.e("Entity Response : ", entityResponse); 

      jsonArray = new JSONArray(entityResponse); 

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

    return jsonArray; 


} 

}

PHP скрипт

<?php 

    $db_host = 'localhost'; 
    $db_name = 'abx'; 
    $db_user= 'abx'; 
    $user_pw = 'abx'; 

//PDO is a extension which defines a lightweight, consistent interface for accessing databases in PHP. 
$dbn='mysql:host='.$db_host.'; dbname='.$db_name; 

    try { 
     $db=new PDO('mysql:host='.$db_host.'; dbname='.$db_name,$db_user,$user_pw); 
    } 
    catch (PDOException $e) { 
     $error_message = $e->getMessage(); 
     echo "this is displayed because an error was found"; 
     exit(); 
} 


//here prepare the query for analyzing, prepared statements use less resources and thus run faster 
$row=$db->prepare('select itemName, itemDescription, itemPrice from tblMenu'); 

$row->execute();//execute the query 
$json_data=array();//create the array 
foreach($row as $rec)//foreach loop 
{ 
$json_array['name']=$rec['itemName']; 
    $json_array['desc']=$rec['itemDescription']; 
    $json_array['price']=$rec['itemPrice']; 
//here pushing the values in to an array 
    array_push($json_data,$json_array); 

} 

//built in PHP function to encode the data in to JSON format 
echo json_encode($json_data); 





?> 

Я бы признателен, если кто-то может помочь мне, это начало двигаться Теперь меня с ума ....

ответ

0

Put это в onCreate:

// Gain access so I can change the TextViews 
TextView line1 = (TextView)findViewById(R.id.name_result); 
TextView line2 = (TextView)findViewById(R.id.desc_result); 
TextView line3 = (TextView)findViewById(R.id.price_result); 
0

Ваша страница PHP не возвращает формат JSON.

Вот что я вижу:

<html> 
<head> 

    <title> Head </title> 

</head> 
<body> 
[{"name":"Hash Tikka","desc":"Spicy barbecued duck","price":"4.15"},{"name":"Lamb or Chicken Tikka","desc":"Spicy pieces of barbecued Lamb or Chicken","price":"4.10"}] 
</body> 
</html> 

Это не допустимый формат JSON, как это JSON в HTML.

Извлеките HTML-код и снова проверьте свой синтаксический анализ.

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