2015-06-24 3 views
0

мне нужно изменить JSON использовать анализатор Джексоном, , потому что это приложение синтаксического анализа данных больше, чем первоначально планировалось,андроида от jsonparser изменения джексон

tempActivity.java

package com.xxx.xxx; 

import java.io.UnsupportedEncodingException; 
import java.net.URLEncoder; 
import java.util.ArrayList; 
import java.util.HashMap; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.text.Editable; 
import android.text.TextWatcher; 
import android.view.View; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.AbsListView; 
import android.widget.AdapterView; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.xxx.xxx.libs.JSONParser; 

public class tempActivity extends MainActivity { 
    ListView list; 
    TextView name; 
    TextView intro; 
    TextView info; 
    tempLazyAdapter adapter; 
    String searchStr; 

    //Button Btngetdata; 
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>(); 
    //URL to get JSON Array 
    private static String url = "http:/xxx/json.php?keyword="; 
    private static String pageurl = "&page="; 
    //private static String encodedurl = "http://www.ebuddha.org/temp_json.php"; 
    //String url= getResources().getString(R.string.temp_url); 
    //JSON Node Names 
    String encodedurl = url; 
    private static final String TAG_OS = "temp"; 
    private static Context mContext; 
    JSONArray temp = null; 
    JSONArray tmp_temp = null; 
    JSONArray newtemp = null; 

    private int preLast; 
    // Flag for current page 
    int current_page = 1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     Intent intent = this.getIntent(); 
     Bundle bundle = intent.getExtras(); 
     mContext = getApplicationContext(); 

     if(bundle.getString("keyword") != null){ 
      // Getting JSON from URL 
      try { 
       searchStr = URLEncoder.encode(bundle.getString("keyword"),"UTF-8"); 
       encodedurl = url + searchStr + pageurl + current_page ; 

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

     } 

     acttemp = true; 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_temp); 

     final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); 
     if (activeNetwork != null && activeNetwork.isConnected()) { 
      //notify user you are online 
      oslist = new ArrayList<HashMap<String, String>>(); 
      new JSONParse().execute(); 
     } else { 
      //notify user you are not online 
      Toast.makeText(tempActivity.this, R.string.disconnect, Toast.LENGTH_SHORT).show(); 
     } 

     final EditText edittext = (EditText) findViewById(R.id.eText_search); 
     edittext.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { } 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { } 
      @Override 
      public void afterTextChanged(Editable s) { 
       if (s.length() > 0) { 
        // TODO Auto-generated method stub 
        char lastCharacter = s.charAt(s.length() - 1); 

        if (lastCharacter == '\n') { 
         String instr = s.subSequence(0, s.length() - 1).toString(); 
         try { 
          current_page = 1; 
          searchStr = URLEncoder.encode(instr,"UTF-8"); 
          encodedurl = url + searchStr + pageurl + current_page; 
         } catch (UnsupportedEncodingException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
         if (activeNetwork != null && activeNetwork.isConnected()) { 
          //notify user you are online 
          oslist = new ArrayList<HashMap<String, String>>(); 
          new JSONParse().execute(); 
         } else { 
          //notify user you are not online 
          Toast.makeText(tempActivity.this, R.string.disconnect, Toast.LENGTH_SHORT).show(); 
         } 
         edittext.setText(""); 
         InputMethodManager imm = (InputMethodManager)getSystemService(
           Context.INPUT_METHOD_SERVICE); 
         imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); 
        } 
       } 
      } 
     }); 

     // Implementing scroll refresh 
     list.setOnScrollListener(new AbsListView.OnScrollListener() { 
      @Override 
      public void onScrollStateChanged(AbsListView absListView, int i) { 
      } 

      @Override 
      public void onScroll(AbsListView absListView, int firstItem, int visibleItemCount, final int totalItems) { 
       // Log.e("Get position", "--firstItem:" + firstItem + " visibleItemCount:" + visibleItemCount + " totalItems:" + totalItems + " pageCount:" + pageCount); 
       int total = firstItem + visibleItemCount; 
       final int lastItem = firstItem + visibleItemCount; 

       // Total array list i have so it 
       //if (pageCount < 2) { 

        if (total == totalItems) { 
         if(preLast!=lastItem){ 

          preLast = lastItem; 
         current_page++; 
         encodedurl = url + searchStr + pageurl + current_page; 
         new JSONParse().execute(); 

         } 
        } 
       //} else { 
       // Log.e("hide footer", "footer hide"); 
       // listView.removeFooterView(footer); 
       //} 
      } 

     });   

    } 

    @Override 
    public void onDestroy() 
    { 
     if(list != null){ 
      list.setAdapter(null); 
     } 
     super.onDestroy(); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     System.gc(); 
    } 

    private class JSONParse extends AsyncTask<String, String, JSONObject> { 
     private ProgressDialog pDialog; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      list=(ListView)findViewById(R.id.list); 


      name = (TextView)findViewById(R.id.name); 
      intro = (TextView)findViewById(R.id.intro); 
      info = (TextView)findViewById(R.id.info); 
      pDialog = new ProgressDialog(tempActivity.this); 
      pDialog.setMessage(getString(R.string.load_temp_data)); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.setCanceledOnTouchOutside(false); 
      pDialog.show(); 


     } 
     @Override 
     protected JSONObject doInBackground(String... args) { 
      JSONParser jParser = new JSONParser(); 
      JSONObject json = jParser.getJSONFromUrl(encodedurl); 
      return json; 
     } 


     @Override 
     protected void onPostExecute(JSONObject json) { 
      pDialog.dismiss(); 
      try { 
       // Getting JSON Array from URL 
       if(current_page <= 1){ 
        temp = json.getJSONArray(TAG_OS); 
        adapter=new tempLazyAdapter(mContext, tempActivity.this, temp); 
        list.setAdapter(adapter); 
        list.setOnItemClickListener(new DrawerItemClickListener()); 
       }else{ 
        newtemp = json.getJSONArray(TAG_OS); 
        for (int i = 0; i < newtemp.length(); i++) { 
         temp.put(newtemp.get(i)); 
         } 

        adapter.notifyDataSetChanged(); 
        //list.setAdapter(adapter); 
       } 

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

     private class DrawerItemClickListener implements ListView.OnItemClickListener { 
     @Override 
     public void onItemClick(AdapterView parent, View view, int position, long id) { 
      //selectItem(position); 
      TextView tid = (TextView) view.findViewById(R.id.tid); 
      String selectTid = tid.getText().toString(); 
      //Toast.makeText(tempActivity.this, "click:" + selectTid, Toast.LENGTH_SHORT).show(); 

      Intent tempInfoIntent = new Intent(tempActivity.this, 
        tempInfoActivity.class); 
      Bundle bundle = new Bundle(); 
      bundle.putString("tid", selectTid); 
      tempInfoIntent.putExtras(bundle); 
      startActivity(tempInfoIntent);  
     } 
    } 

    } 
} 

С JSON Я разборе это следующим образом : JSONParser.java

package com.xxx.xxx.libs; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.URL; 

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

import android.util.Log; 

//import com.xxx.xxx.ImageLoader; 
public class JSONParser { 
    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 
     //imageLoader = new ImageLoader(activity.getApplicationContext()); 
    } 
    public JSONObject getJSONFromUrl(String url) { 
     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      /* 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     // return JSON String 
     return jObj; 
    } 
} 

, потому что это приложение нужно наилучшую производительность. большое спасибо.

ответ

0

Я бы рекомендовал вам использовать Джексон в сочетании с Retrofit, который построен на RxJava. Поэтому вам не нужно заботиться о задачах async. Библиотека сделает все для вас.

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