2017-03-31 46 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. 持有人模式

你的问题太宽。一旦你用你的代码正确启动,不断询问。

相关问题