【问题标题】:Create table rows dynamically from parsed JSON in AsyncTask in Android在 Android 的 AsyncTask 中从解析的 JSON 动态创建表行
【发布时间】:2016-07-11 12:41:28
【问题描述】:

我现在有点卡住了。我想从解析的 JSON 数据创建一个表。通过单击按钮使用 AsyncTask 从 Web 服务获取 JSON。然后在 AsyncTask 中解析获取的 json。我想并行创建一个表格布局并将其显示在用户界面上。我已经包含了 AsyncTask 类。 例如:我的 JSON 是 [{"Instrument":"EURCAD"},{"Entry Price","1.453"}]

表格应该是这样的:

|仪器 |入门价格|

|欧元加元 | 1.453 |

请帮忙!!!

异步任务

package com.shubhamhpcs.fetchdb;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
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.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Satyam on 7/11/2016.
 */
public class FetchInstrumentTask extends AsyncTask<Void,Void,String[]> {
    private final String LOG_TAG = FetchInstrumentTask.class.getSimpleName();

    //To parse JSON String recieved from the server
    public String[] getInstrumentDataFromJson(String forecastJsonStr)

        throws JSONException {
            String[] resultStrs = new String[12];
            final String OWM_INSTRUMENT ="Instrument";
            final String OWM_NEW_SIGNAL ="NewSignal";
            final String OWM_ENTRY_TYPE ="EntryType";
            final String OWM_ENTRY_PRICE ="EntryPrice";
            final String OWM_TRAILING_STOP_1 ="TrailingStop1";
            final String OWM_TRAILING_STOP_2 ="TrailingStop2";
            final String OWM_TGT ="TGT";
            final String OWM_TGT_HIT ="TGTHit";
            final String OWM_P_L ="P&L";
            final String OWM_STOP_LOSS ="StopLoss";

            JSONArray instrumentArray = new JSONArray(forecastJsonStr);
            for (int i = 0; i < instrumentArray.length(); i++) {
                JSONObject instrumentObject = instrumentArray.getJSONObject(i);

                String instrumentName = instrumentObject.getString(OWM_INSTRUMENT);
                String newSignal = instrumentObject.getString(OWM_NEW_SIGNAL);
                double EntryType = instrumentObject.getDouble(OWM_ENTRY_TYPE);
                double EntryPrice = instrumentObject.getDouble(OWM_ENTRY_PRICE);
                double trailingStop1 = instrumentObject.getDouble(OWM_TRAILING_STOP_1);
                double trailingStop2 = instrumentObject.getDouble(OWM_TRAILING_STOP_2);
                double tgt = instrumentObject.getDouble(OWM_TGT);
                String tgtHit = instrumentObject.getString(OWM_TGT_HIT);
                String pl = instrumentObject.getString(OWM_P_L);
                String stopLoss = instrumentObject.getString(OWM_STOP_LOSS);
                resultStrs[i] = instrumentName + "|" + newSignal + " | " + EntryType + " | " + EntryPrice + "|" + trailingStop1 + "|" +
                        trailingStop2 + "|" + tgt + "|" + tgtHit + "|" + pl + "|" + stopLoss ;
            }

            for (String s : resultStrs) {
                Log.v(LOG_TAG, "Instrument entry: " + s);
            }
            return resultStrs;
        }

    @Override
    protected String[] doInBackground(Void... voids) {
        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String instrumentJsonStr = null;

        try {

            URL url = new URL("http://192.168.1.101/tooth/index.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return null;
            }
            instrumentJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("FetchInstrumentTask", "Error ", e);
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("Fetch", "Error closing stream", e);
                }
            }
        }
        Log.v("FetchInstrumentTask  ","Data from VPS is: "+instrumentJsonStr);
        try {
            return getInstrumentDataFromJson(instrumentJsonStr);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        }
        return null;
    }
}

MainActivity

package com.shubhamhpcs.fetchdb;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class Main2Activity extends AppCompatActivity {

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


    public void getjson(View view){
        FetchInstrumentTask fetchInstrumentTask =new FetchInstrumentTask();
        fetchInstrumentTask.execute();
    }
}

【问题讨论】:

    标签: android json android-asynctask


    【解决方案1】:

    让我们创建一个Instrument 类,其中包含工具名称和价格,它比字符串更好。

    您的 AsyncTask 将返回仪器列表 List&lt;Instrument&gt;,而不是 String[]

    然后向您的AsyncTask 引入一个方法onPostExecute,它将向Activity 提供数据。例如,您可以使活动实现一个接口IInstrumentsDisplay,该接口将具有一个方法void showInstruments(List&lt;Instrument&gt;)。然后,您将使用对此接口(活动)的引用来初始化 AsyncTask。

    在此方法showInstruments 中,您将在活动中构造一个适配器,例如ArrayAdapter&lt;Instrument&gt;,您将使用AsyncTask 返回的数据进行初始化,然后指向您的ListView(这将显示表)到这个适配器。

    您的活动将在其布局 xml 中包含一个 ListView,您还需要定义一个项目行 xml 布局文件,并且在适配器中您将覆盖 getView() 方法以在正确的位置显示名称和价格行。

    【讨论】:

      【解决方案2】:

      试试这个

       try {
              JSONObject jsonObject=array.getJSONObject(0);
              ArrayList<String> headers=getKeys(jsonObject);
      
              TableRow row=(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row, null);
      
              //user the first row as the header
              for (int i=0;i<headers.size();i++){
                  //TextView textView=new TextView(context);
                  TextView textView = (TextView)((Activity)context).getLayoutInflater().inflate(R.layout.template_text_medium, null);
      
                  textView.setText(headers.get(i));
                  row.addView(textView);
              }
              table.addView(row);
      
              for (int j=0;j<array.length();j++){
                  JSONObject jObj=array.getJSONObject(j);
                  ArrayList<String> values=getValues(jObj);
      
                  TableRow new_row=null;
                  if (j==array.length()-1){
                     new_row =(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row_last, null);
                  }
                  else {
                      new_row =(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row, null);
                  }
      
                  for (int i=0;i<values.size();i++){
                      String value=values.get(i);
                      if (value.equals("null"))
                          value="";
                      TextView textView = (TextView)((Activity)context).getLayoutInflater().inflate(R.layout.template_text_medium, null);
                      textView.setText(value);
                      new_row.addView(textView);
                  }
                  table.addView(new_row);
              }
      
      
      
          } catch (JSONException e) {
              e.printStackTrace();
          }
      

      【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 2018-12-28
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多