2015-06-03 2 views
0

Здесь мое приложение, когда я ввожу повод № 17603 текст редактирования и кнопку ввода. Я исправлю его, получаю файл traindetails.txt из папки assets и конвертирую в строку, а затем передаю строку в json array. Он будет показан в logcat. Здесь я не получаю никаких ошибок.Данные JSON Array, получаемые из активов

JSON Requset хранится в .txt месте в папке Assets

{ 
    "status":"OK", 
    "result":{ 
     "trainno":"17603", 
     "route":[ 
      { 
      "code":"KCG", 
      "name":"Kacheguda", 
      "arr":"First", 
      "dep":"21:00", 
      "day":1, 
      "stop":"Y", 
      "dts":"2.5" 
      } 
     ] 
    } 
} 



Основная активность

package com.example.trainroutes; 
    import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 
    import org.json.JSONArray; 
    import org.json.JSONException; 
    import org.json.JSONObject; 

    import android.support.v7.app.ActionBarActivity; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.view.Menu; 
    import android.view.MenuItem; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.ListView; 
    import android.widget.Toast; 

    public class MainActivity extends ActionBarActivity implements OnClickListener { 
     private EditText train_search_editText; 
     private Button submit_button; 
     private ListView train_listview; 

     // private String jsonStirng ; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      train_search_editText = (EditText) findViewById(R.id.trainSearch); 
      submit_button = (Button) findViewById(R.id.search_train_button); 
      train_listview = (ListView) findViewById(R.id.trian_name_listview); 
      submit_button.setOnClickListener(this); 


     } 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if (train_search_editText.getText().toString().equals("17603")) { 
       try { 
        // Reading text file from the assets folder 
        StringBuffer stringBuffer = new StringBuffer(); 
        BufferedReader bufferReader = null; 
        try { 
         bufferReader = new BufferedReader(new InputStreamReader(
           getAssets().open("traindetails.txt"))); 
         String temp; 
         while ((temp = bufferReader.readLine()) != null) { 
          stringBuffer.append(temp); 
         } 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } finally { 
         try { 
          bufferReader.close(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
        } 
        String jsonStirng = stringBuffer.toString(); 
        Log.e("Json String", "JSON String"+jsonStirng); 
        // creating jsonobject from string 

        JSONObject jsonMainObj = new JSONObject(jsonStirng); 
        // creating json array from json object 

        JSONArray jsonArrayObject = jsonMainObj.getJSONArray("route"); 
        for (int i = 0; i < jsonArrayObject.length(); i++) { 
         JSONObject jsonObject = jsonArrayObject.getJSONObject(i); 
         // getting data from individual object 
         String code = jsonObject.getString("code"); 
         String name = jsonObject.getString("name"); 
         String arr = jsonObject.getString("arr"); 
         String dep = jsonObject.getString("dep"); 
         int day = jsonObject.getInt("day"); 
         String stop = jsonObject.getString("stop"); 
         String dts = jsonObject.getString("dts"); 

         Log.d("JSONObject", "train " + name.toString()); 
        } 

       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } else { 
       Toast.makeText(getApplicationContext(), "Invalid ", 
         Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 
+0

что вы хотите точно? в чем дело? –

+0

привет syed, когда я вхожу в поезд no 17603 в edittext и вводим submit buton.it будет correct.it будет получать данные из папок активов .txt и передаваться в json-массив – teju

+0

привет syed, выше программа правильная или неправильная – teju

ответ

0

Используйте этот код

package com.example.trainroutes; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.Toast; 

public class MainActivity extends ActionBarActivity implements OnClickListener { 
    private EditText train_search_editText; 
    private Button submit_button; 
    private ListView train_listview; 

    // private String jsonStirng ; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     train_search_editText = (EditText) findViewById(R.id.trainSearch); 
     submit_button = (Button) findViewById(R.id.search_train_button); 
     train_listview = (ListView) findViewById(R.id.trian_name_listview); 
     submit_button.setOnClickListener(this); 


    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     if (train_search_editText.getText().toString().equals("17603")) { 
      try { 
       // Reading text file from the assets folder 
       StringBuffer stringBuffer = new StringBuffer(); 
       BufferedReader bufferReader = null; 
       try { 
        bufferReader = new BufferedReader(new InputStreamReader(
          getAssets().open("traindetails.txt"))); 
        String temp; 
        while ((temp = bufferReader.readLine()) != null) { 
         stringBuffer.append(temp); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        try { 
         bufferReader.close(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
       String jsonStirng = stringBuffer.toString(); 
       Log.e("Json String", "JSON String"+jsonStirng); 
       // creating jsonobject from string 

       JSONObject jsonMainObj = new JSONObject(jsonStirng); 

JSONObject jsonresultObject=jsonMainObj.getJsonObject("result") 
       // creating json array from json object 

       JSONArray jsonArrayObject = jsonresultObject.getJSONArray("route"); 
       for (int i = 0; i < jsonArrayObject.length(); i++) { 
        JSONObject jsonObject = jsonArrayObject.getJSONObject(i); 
        // getting data from individual object 
        String code = jsonObject.getString("code"); 
        String name = jsonObject.getString("name"); 
        String arr = jsonObject.getString("arr"); 
        String dep = jsonObject.getString("dep"); 
        int day = jsonObject.getInt("day"); 
        String stop = jsonObject.getString("stop"); 
        String dts = jsonObject.getString("dts"); 

        Log.d("JSONObject", "train " + name.toString()); 
       } 

      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } else { 
      Toast.makeText(getApplicationContext(), "Invalid ", 
        Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 
+0

очень приветствуется !! пожалуйста, примите ответ. – Sakshi

1

вот как вы должны делать

String jsonString = loadJSONFromAsset(getApplicationContext()); 

    try { 
     JSONObject jsonMainObj = new JSONObject(jsonString); 


     JSONObject jsonArrayObjectResult = jsonMainObj.getJSONObject("result"); 
     JSONArray jsonArrayObjectRoute = jsonArrayObjectResult.getJSONArray("route"); 
     for (int i = 0; i < jsonArrayObjectRoute.length(); i++) { 
      JSONObject jsonObject = jsonArrayObjectRoute.getJSONObject(i); 
      // getting data from individual object 
      String code = jsonObject.getString("code"); 
      String name = jsonObject.getString("name"); 
      String arr = jsonObject.getString("arr"); 
      String dep = jsonObject.getString("dep"); 
      int day = jsonObject.getInt("day"); 
      String stop = jsonObject.getString("stop"); 
      String dts = jsonObject.getString("dts"); 

      Log.d("JSONObject", "train " + name.toString()); 
     } 


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

public String loadJSONFromAsset(Context mContext) { 
    String json = null; 
    try { 

     InputStream is = mContext.getAssets().open("test.json"); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     json = new String(buffer, "UTF-8"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return json; 

} 
+0

thaks Syed.it очень полезен для меня thaks много – teju

+0

вы хорошо приходите, я рад помочь вам, счастливое кодирование :) –

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