在Android中的AsyncTask中通过解析的JSON动态创建表行

时间:2016-07-11 12:41:29

标签: android json android-asynctask

我现在有点困难。我想从解析的JSON数据创建一个表。只需单击一个按钮就可以使用AsyncTask从Web服务中获取JSON。然后在AsyncTask中解析获取的json。我想平行创建一个表格布局并在用户界面上显示它。我已经包含了AsyncTask类。 例如:我的JSON是[{“工具”:“EURCAD”},{“入场价”,“1.453”}]

表格应如下所示:

|仪器| EntryPrice |

| EURCAD | 1.453 |

请帮助!!!

AsyncTask

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();
    }
}

2 个答案:

答案 0 :(得分:0)

让我们制作一个Instrument类,其中包含乐器名称和价格,这比Strings更好。

您的AsyncTask将返回工具列表List<Instrument>,而不是String[]

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

在活动中的这个方法showInstruments中,您将构建一个适配器,例如ArrayAdapter<Instrument>,您将使用AsyncTask返回的数据初始化,然后指向您的{{ 1}}(将显示表格)到此适配器。

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

答案 1 :(得分:0)

试试这个

 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();
    }