我有一个活动,其中包含一个编辑文本,按钮和Textview。 现在我想如果有人在编辑文本中输入Java,则其信息为 填充在文本视图中。这是我的JSON。我还包括了我的.java文件。
{
"compscience": [
{
"bookname": "java",
"row": "1",
"column": "1"
},
{
"bookname": "cns",
"row": "2",
"column": "2"
},
{
"bookname": "rdbms",
"row": "3",
"column": "3"
},
{
"bookname": "daa",
"row": "4",
"column": "4"
}
]
}
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class act1 extends AppCompatActivity {
EditText subname;
Button fetch;
static String ab,single="";
public static String c;
static TextView data;
fetchdata process;
StringBuffer response ;
void init()
{
subname = findViewById(R.id.subname);
ab = subname.toString();
fetch = findViewById(R.id.button);
data=findViewById(R.id.result);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act1);
init();
}
public void fetch(View view)
{
process = new fetchdata();
process.execute();//it will start do in background
}
class fetchdata extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
response = new StringBuffer();
try {
URL url = new URL("https://api.myjson.com/bins/c1054");
URLConnection connection =url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader buffer = new BufferedReader(reader);
String line = "";
while((line = buffer.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
try {
JSONArray array=new JSONArray("respnse");
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(ab.equals(obj.getString("booknmae")))
{
single = single +obj.getString("row");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
act1.data.setText(single);
}
}
}
答案 0 :(得分:1)
首先,您需要了解JSONObject
和JSONArray
的工作方式,您的json响应为JSONObject
,并且在其中有名称为compscience
的密钥具有{{ 1}}作为值。
尝试一下:
JSONArray