大家好我正在开发一个应用程序,它从虚假站点休息蜜蜂收集数据并将它们存储在listView中。到目前为止,我设法下载了JSON文件并将其显示在listView中。这些是我的课程:
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中显示。 在此先感谢您的帮助。
答案 0 :(得分:-1)
试试这些链接:
Json Parsing:
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
数据库:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
这些将为您提供如何处理这些事情的好主意。
答案 1 :(得分:-1)
如果您要求了解下一步操作的最佳做法,并且您不想阅读完整的Code Apprentice,请阅读有关此内容的基础知识。希望它有所帮助
你的问题太宽了。一旦你正确使用你的代码,继续问。