2016-04-16 2 views
0

Я новичок в разработке Android, и я изо всех сил пытаюсь рисовать некоторые графики после HTTP-запроса в базу данных Mysql. Я просмотрел SyncTask, настраиваемый метод View и onDraw, но я должен что-то упустить, потому что я просто не могу заставить его работать. В основном HTTP-запрос выбирает некоторые записи из db (я получил эту работу), и мне нужно создать граф с данными. HTTP-запрос - это асинхронный процесс, поэтому к моменту завершения HTTP-запроса метод onDraw был выполнен без данных, поэтому я начал изучать SyncTask, но мне не удается передать массив, в котором хранятся данные, которые будут нарисованы из метода onPostExecute. Любая помощь будет принята с благодарностью, и если вы укажете на какой-нибудь примерный код, который будет замечательным. СпасибоКак реализовать ondraw после httprequest в базу данных

+0

показать код. –

ответ

0

Вот код, который я нашел в Интернете, и я пытался заставить его работать, пока я могу получить данные, чтобы упростить его. Я только работаю с полем, и я хочу рисовать текст местонахождение:

public class TestFragment extends Fragment { 

    private static final String TAG = "AsyncTestFragment"; 

    // get some fake data 
    private static final String TEST_URL     = "http://jsonplaceholder.typicode.com/comments"; 
    //private static final String TEST_URL     = "http://localhost/~juan/A_get_tanks.php"; 
    private static final String ACTION_FOR_INTENT_CALLBACK = "THIS_IS_A_UNIQUE_KEY_WE_USE_TO_COMMUNICATE"; 

    ProgressDialog progress; 

    @Override 
    public View onCreateView(LayoutInflater inflater, 
          ViewGroup container, 
          Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_test, container, false); 
    } 


    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     getContent(); 
    } 

    private void getContent() { 
     // the request 
     try { 
      HttpGet httpGet = new HttpGet(new URI(TEST_URL)); 
      RestTask task = new RestTask(getActivity(), ACTION_FOR_INTENT_CALLBACK); 
      task.execute(httpGet); 
      progress = ProgressDialog.show(getActivity(), "Getting Data ...", "Waiting For Results...", true); 
     } 
     catch (Exception e) { 
      Log.e(TAG, e.getMessage()); 
     } 

    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     getActivity().registerReceiver(receiver, new IntentFilter(ACTION_FOR_INTENT_CALLBACK)); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     getActivity().unregisterReceiver(receiver); 
    } 

    /** 
    * Our Broadcast Receiver. We get notified that the data is ready, and then we 
    * put the content we receive (a string) into the TextView. 
    */ 
    public BroadcastReceiver receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String location; 
      // clear the progress indicator 
      if (progress != null) { 
       progress.dismiss(); 
      } 
      String response = intent.getStringExtra(RestTask.HTTP_RESPONSE); 
      try { 
       JSONObject mainObject = new JSONObject(response); 
       JSONArray tank_data = mainObject.getJSONArray("tank_data"); 
       JSONObject tankObj = tank_data.getJSONObject(0); 
       location = (String) tankObj.getString("Location"); 

      } catch (JSONException e) { 
       location = null; 
       e.printStackTrace(); 
      } 

      new TankView(context, location); 
      Log.i(TAG, "RESPONSE = " + location); 

     } 
    }; 

} 

public class RestTask extends AsyncTask<HttpUriRequest, Void, String> 
{ 
    private static final String TAG = "AsyncRestTask"; 
    public static final String HTTP_RESPONSE = "httpResponse"; 

    private Context mContext; 
    private HttpClient mClient; 
    private String mAction; 

    public RestTask(Context context, String action) { 
     mContext = context; 
     mAction = action; 
     mClient = new DefaultHttpClient(); 
    } 

    public RestTask(Context context, String action, HttpClient client) { 
     mContext = context; 
     mAction = action; 
     mClient = client; 
    } 

    @Override 
    protected String doInBackground(HttpUriRequest... params) { 
     try { 
      HttpUriRequest request = params[0]; 
      HttpResponse serverResponse = mClient.execute(request); 
      BasicResponseHandler handler = new BasicResponseHandler(); 
      return handler.handleResponse(serverResponse); 
     } 
     catch (Exception e) { 
      // TODO handle this properly 
      e.printStackTrace(); 
      return ""; 
     } 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     Log.i(TAG, "RESULT = " + result); 
     Intent intent = new Intent(mAction); 
     intent.putExtra(HTTP_RESPONSE, result); 

     // broadcast the completion 
     mContext.sendBroadcast(intent); 
    } 

} 

package com.alvinalexander.asynctest; 

import android.app.Activity; 
import android.content.res.Configuration; 
import android.os.Bundle; 

public class TestActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     if (savedInstanceState == null) { 
      TestFragment testFragment = new TestFragment(); 
      getFragmentManager().beginTransaction().add(android.R.id.content, testFragment).commit(); 
      setContentView(new TankView(this, "")); 
     } 
    } 

} 

public class TankView extends View { 

    private String location; 
    private Paint _paintTank = new Paint(); 

    public TankView(Context context, String location) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     init(null, 0); 
     this.location = location; 
    } 

    public TankView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     // TODO Auto-generated constructor stub 
     init(attrs, 0); 
    } 

    public TankView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     // TODO Auto-generated constructor stub 
     init(attrs, 0); 
    } 

    public TankView(TestActivity testActivity, String location) { 
     super(testActivity); 
     this.location = location; 

    } 

    public TankView(TestActivity testActivity, Object o) { 
     super(testActivity, (AttributeSet) o); 
    } 

    private void init(AttributeSet attrs, int defStyle) { 
     _paintTank.setColor(Color.RED); 
     _paintTank.setAntiAlias(true); 
     _paintTank.setStyle(Paint.Style.STROKE); 
    } 



    @Override 
    public void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     if (this.location != null) { 
      canvas.drawText(this.location, 10, 10, _paintTank); 
     } 
    } 
} 

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:background="#AEECFF"> 

    <!-- fill the screen with a textview. the app will write text into it. --> 

    <com.alvinalexander.asynctest.TankView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</RelativeLayout> 
Смежные вопросы