2017-03-31 84 views
-2

大家好,我正在開發一個應用程序,它從一個假的網站收集數據休息蜜蜂並將它們存儲在一個listView中。到目前爲止,我設法下載JSON文件並將其顯示在listView中。這些都是我的課:解析Json並將數據存儲在sqlite數據庫中並查看列表查看

HomeScreen.java

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.util.ArrayList; 
import java.util.HashMap; 

public class HomeScreen extends AppCompatActivity { 
    private String classtag= HomeScreen.class.getSimpleName(); //return 
     name of underlying class 
    private ListView lv; 
    private ProgressDialog progress; 
    private String url="https://jsonplaceholder.typicode.com/posts"; 
    //passing url 
    ArrayList<HashMap<String,String>> studentslist; //arraylist to save key 
    value pair from json 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_home_screen); 
     studentslist=new ArrayList<>(); 
     lv= (ListView) findViewById(R.id.list); //from home screen listview 
     new getStudents().execute(); // it will execute your AsyncTask 
    } 
//--------------------------//-------------------------------//---------------------// 
    public class getStudents extends AsyncTask<Void,Void,Void> { 
     protected void onPreExecute(){ 
      super.onPreExecute(); //it will use pre defined preExecute 
            method in async task 
      progress=new ProgressDialog(HomeScreen.this); 
      progress.setMessage("Fetching JSON.,."); // show what you want 
                 in the progress dialog 
      progress.setCancelable(false); //progress dialog is not 
              cancellable here 
      progress.show(); 
     } 
     protected Void doInBackground(Void...arg0){ 
      HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler 
      String jString = hh.makeHTTPCall(url); //calling makeHTTPCall 
            method and string its response in a string 
      Log.e(classtag, "Response from URL: " + jString); 
      if (jString != null) { 
      try { 
       JSONArray students = new JSONArray(jString); 
       //our json data starts with the object 
       //fetch array from studentsinfo object 
       for (int i = 0; i < students.length(); i++) { 
        JSONObject obj = students.getJSONObject(i); //get object 
                   from i index 
        String userId=obj.getString("userId"); //save string 
              from variable 'id' to string 
        String id=obj.getString("id"); 
        String title=obj.getString("title"); 
        String body=obj.getString("body"); 
        HashMap<String, String> studentdata = new HashMap<>(); 
         //create a hash map to set key and value pair 

        studentdata.put("userId", userId); //hash map will save 
                key and its value 
        studentdata.put("id", id); 
        studentdata.put("title", title); 
        studentdata.put("body", body); 

        studentslist.add(studentdata); //now save all of the key 
                value pairs to arraylist 
       } 
      } catch (final JSONException e) { 
       Log.e(classtag, "Json parsing error: " + e.getMessage()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Json parsing error: " + e.getMessage(), 
           Toast.LENGTH_LONG) 
           .show(); //show if you catch any exception 
                   with data 
        } 
       }); 
      } 
     } else { 
      Log.e(classtag, "Couldn't get json from server."); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() {Toast.makeText(getApplicationContext(), 
         "Couldn't get json from server. Check internet 
                connection!", 
         Toast.LENGTH_LONG).show();//show if you are unable 
         to connect with the internet or if jString is null 
       } 
      }); 
     } 
     return null; 
    } 
    protected void onPostExecute(Void Result){ 
     super.onPostExecute(Result); 
     if(progress.isShowing()){ 
      progress.dismiss(); 
     } 
     ListAdapter adapter=new SimpleAdapter(
       HomeScreen.this, 
       studentslist, 
       R.layout.bucket_list, 
       new String[]{"userId","id","title","body"}, 
       new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address 
                 ,R.id.list_Gender}); 
     lv.setAdapter(adapter); 

     } 
    } 
} 

Http_Handler.java

import android.util.Log; 
import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.ProtocolException; 
import java.net.URL; 

public class HTTP_Handler { 
     private static final String classtag= 
     HTTP_Handler.class.getSimpleName(); //return name of underlying class 

public String makeHTTPCall(String URLinput) { // method which will request 
       to server when provided with url 
    String response = null; 
    try { 
     URL url = new URL(URLinput); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
       //to open connection with url 
     conn.setRequestMethod("GET"); //request type is of GET, which 
          means to get information from the server 

     InputStream in = new BufferedInputStream(conn.getInputStream()); 
     //storing the input stream we are getting for the url 
     response = InputStreamToString(in); //now storing string from the 
              input stream 
    } catch (MalformedURLException e) { 
     Log.e(classtag, "MalformedURLException: " + e.getMessage()); 
    } catch (ProtocolException e) { 
     Log.e(classtag, "ProtocolException: " + e.getMessage()); 
    } catch (IOException e) { 
     Log.e(classtag, "IOException: " + e.getMessage()); 
    } catch (Exception e) { 
     Log.e(classtag, "Exception: " + e.getMessage()); 
    } 
    return response; //returning whatever we fetching from the string to the 
        method. 
    } 
private String InputStreamToString(InputStream is) { //fetching string 
    form the input stream 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it 
    will read form stream 
    StringBuilder sb = new StringBuilder(); 
    String line; 
    try { 
     while ((line = br.readLine()) != null) { 
      sb.append(line).append('\n'); //whatever we read from the 
      stream, we will append it to the stringbuilder 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
      } catch (IOException e) { 
      e.printStackTrace(); 
      } 
     } 
    return sb.toString(); 
    } 
} 

有人能幫助我在SQLite數據庫和顯示節能集成曾經在ListView。 在此先感謝您的幫助。

+1

您是否閱讀過有關如何連接SQLite數據庫的在線文檔和教程?你遇到了什麼具體問題? –

+0

因爲我是初學者,所以我想要一個完整的畫面繼續下去。 –

+0

然後,您應該閱讀http://developer.android.com上的Android文檔。 –

回答

-1

如果您要求下一步做什麼的最佳實踐,並且您不想閱讀完整的代碼學徒,請閱讀關於此的基礎知識。希望它可以幫助

  1. Java組件(getter和setter方法)
  2. GSON或任何其他工具從JSON轉換爲對象,反之亦然
  3. 如何存儲/一個SQL連接檢索您的對象/從SQLite的
  4. 回收站查看
  5. 持有人模式

你的問題太寬。一旦你用你的代碼正確啓動,不斷詢問。

相關問題