I'm working on an Android app that uses spinner and was connected to a MySQL server, but it seems that the dropdown list is not showing on the spinner.
package edu.sti.mobileinstructorevaluation;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://10.0.2.2:8080/mobieva/getcourse.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("cname"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
}
Related
I have three values to send to MainActivity. the JSONObject json is arriving with the correct value, but this value is not being accessed in try catch, that is, the onPostExecute is only executing pDialog.dismiss () ;.
how do I get the onPostExecute to read internally the try cartch?
MainActivity
package ic.eng.br.testejson;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements Json{
EditText edtUsuario, edtSenha;
Button btnLogin;
TextView textView1, textView2, textView3;
JSONArray user = null;
String url = "http://www.ic.eng.br/android/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUsuario = findViewById(R.id.edtUsuario);
edtSenha = findViewById(R.id.edtSenha);
btnLogin = findViewById(R.id.btnLogin);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
final Asyncexecute asyncexecute = new Asyncexecute(this, this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usuario = edtUsuario.getText().toString();
String senha = edtSenha.getText().toString();
asyncexecute.execute(usuario, senha, url, "");
}
});
}
public void testejson (String Rsenha, String Rprivilegio, String Rperfil) {
textView1.setText(Rsenha);
textView2.setText(Rprivilegio);
textView3.setText(Rperfil);
}
}
Asyncexecute:
package ic.eng.br.testejson;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
#SuppressWarnings("deprecation")
public class Asyncexecute extends AsyncTask <String, String, JSONObject> {
private ProgressDialog pDialog;
private Context context;
JSONArray user = null;
String Rsenha, Rprivilegio, Rperfil;
String usuario, senha, url;
private static final String TAG_USER = "usuario";
private Json execinterface;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public Asyncexecute(Context context, Json execinterface) {
this.execinterface = execinterface;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Carregando");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
usuario = params[0];
senha = params[1];
url = params[2];
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);;
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
user = json.getJSONArray("login");
JSONObject c = user.getJSONObject(0);
Rsenha = c.getString("senha");
Rprivilegio = c.getString("privilegio");
Rperfil = c.getString("perfil");
execinterface.testejson(Rsenha, Rprivilegio, Rperfil);
} catch (JSONException e){
e.printStackTrace();
}
}
}
JSONParser:
package ic.eng.br.testejson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", "tiago"));
nameValuePairs.add(new BasicNameValuePair("senha", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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;
}
}
Joson
package ic.eng.br.testejson;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
public interface Json {
void testejson (String Rsenha, String Rprivilegio, String Rperfil);
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/edtUsuario"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textColor="#D3D3D3"
tools:ignore="Autofill,LabelFor,TextFields"
android:maxLines="1"
android:singleLine="true"
android:digits="abcdefghijklmnopqrstuvxywzç"/>
<EditText
android:id="#+id/edtSenha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="15" />
<Button
android:id="#+id/btnLogin"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Efetuar Login"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
So, the 'selectcode.java' class has some problem with populating values to the android spinners. There is no error in the code, but the thing is i cannot retrieve the values from json file to the spinners. So i thought i am doing wrong some where between JSON objects <-> Array adapter. Can anyone sort it out
MainActivity.java
package com.example.app;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.apache.http.protocol.HTTP;
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.URL;
public class MainActivity extends AppCompatActivity {
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addstep1(View view){
Intent intent = new Intent(this,addcode.class);
startActivity(intent);
}
public void addstep2(View view){
new BackgroundTask().execute();
Intent intent= new Intent(this,selectcode.class);
intent.putExtra("json_data", JSON_STRING);
startActivity(intent);
}
class BackgroundTask extends AsyncTask<Void, Void, String>{
String json_url="JSON_FILE_URL";
#Override
protected String doInBackground(Void... voids){
try {
URL url= new URL(json_url);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder= new StringBuilder();
while ((JSON_STRING=bufferedReader.readLine())!=null){
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
JSON_STRING=result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Select Code.java
package com.example.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class selectcode extends AppCompatActivity {
String JSON_STRING;
List<String> converter = new ArrayList<>();
List<String> zone = new ArrayList<>();
List<String> code = new ArrayList<>();
JSONObject jsonObject;
JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selectcode);
Spinner spinner1=(Spinner) findViewById(R.id.selectconverter);
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, converter);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
Spinner spinner2=(Spinner) findViewById(R.id.selectzone);
ArrayAdapter<String> adapter2=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, zone);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
Spinner spinner3=(Spinner) findViewById(R.id.selectcode);
ArrayAdapter<String> adapter3=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, code);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner3.setAdapter(adapter3);
JSON_STRING= getIntent().getExtras().getString("json_data");
String converternumber,zonenumber,codeid;
try {
jsonObject= new JSONObject(JSON_STRING);
int count=0;
jsonArray= jsonObject.getJSONArray("server_response");
while(count<jsonArray.length()){
JSONObject JO= jsonArray.getJSONObject(count);
converternumber= JO.getString("converternumber");
zonenumber= JO.getString("zonenumber");
codeid= JO.getString("codeid");
adapter1.add(converternumber);
adapter2.add(zonenumber);
adapter3.add(codeid);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSON DATA:
Connected to database{"server_response":[{"converternumber":"0","zonenumber":"","codeid":""},{"converternumber":"1","zonenumber":"23","codeid":"rg"},{"converternumber":"1","zonenumber":"2a","codeid":"test"},{"converternumber":"2","zonenumber":"1a","codeid":"test"},{"converternumber":"1","zonenumber":"1a","codeid":"test 008"},{"converternumber":"1","zonenumber":"2a","codeid":"test001"},{"converternumber":"1","zonenumber":"a1","codeid":"test001"},{"converternumber":"1","zonenumber":"a1","codeid":"test002"},{"converternumber":"1","zonenumber":"a1","codeid":"test003"},{"converternumber":"1","zonenumber":"a1","codeid":"test004"},{"converternumber":"1","zonenumber":"1a","codeid":"test006"},{"converternumber":"1","zonenumber":"1a","codeid":"test007"},{"converternumber":"1","zonenumber":"1a","codeid":"test008"},{"converternumber":"1","zonenumber":"1a","codeid":"test009"},{"converternumber":"1","zonenumber":"1a","codeid":"test010"},{"converternumber":"1","zonenumber":"1a","codeid":"test111"},{"converternumber":"1","zonenumber":"1a","codeid":"test112"},{"converternumber":"1","zonenumber":"12","codeid":"yx"}]}
Try to Use this code
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
You have to notify all your Spinner adapter after adding item on them.
try {
jsonObject= new JSONObject(JSON_STRING);
int count=0;
jsonArray= jsonObject.getJSONArray("server_response");
while(count<jsonArray.length()){
JSONObject JO= jsonArray.getJSONObject(count);
converternumber= JO.getString("converternumber");
zonenumber= JO.getString("zonenumber");
codeid= JO.getString("codeid");
adapter1.add(converternumber);
adapter2.add(zonenumber);
adapter3.add(codeid);
count++;
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
Hope it will help you.
restful service in android authenticating and connecting it to the url
new to android
unable to get the output : username password and connecting to the url
package com.example.newrestapi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText password,userName;
Button login;
ProgressBar progressBar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.editText2);
userName=(EditText) findViewById(R.id.editText1);
login=(Button) findViewById(R.id.button1);
//progess_msz.setVisibility(View.GONE);
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.GONE);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
String s1=userName.getText().toString();
String s2=password.getText().toString();
new ExecuteTask().execute(s1,s2);
}
});
}
class ExecuteTask extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
String res=PostData(params);
return res;
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
//progess_msz.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, 50000).show();
}
}
public String PostData(String[] values) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet("http://myrul");
HttpResponse httpResponse= httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
login authentication using android restful services
I am just programming a data evaluation app for a hydropower station.
There i need to download the data from the server, which ist lying there - as a MySQL table, formatted to a JSON-array.
Now after umpteen hours of work i've done it to connect to the server, download the data and to output it in a auto-generated ListView Layout (with this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results)); )
But this was just a testapplication for the connection.
In the main app i need the dataoutput from the server in a specifiv ListView in one of the Fragments. After again trying around some hours without any success I decided to ask you.
The setListAdapter is not working in a FragmentActivity anymore.
And another question: Is it possible to save those data in specific variables, after downloading it from our server?
Greetings from beatiful Austria,
Duned
package at.duned.hydroevaluation;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.util.List;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Fragment2_DataOutput extends Fragment {
InputStream is;
ArrayList<String> results =new ArrayList<String>();
JSONObject json_data;
TextView tw09;
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
View V=inflater.inflate(R.layout.fragment_2_dataoutput,container, false);
TextView tw09 = (TextView)V.findViewById(R.id.TextView09);
ListView list = (ListView)V.findViewById(R.id.list);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
getData();
//tw09.setText((CharSequence) is);
return V;
}
private void getData() {
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://patrickhartl.lima-city.de/eva1.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Fehler bei der http Verbindung "+e.toString());}
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();
result=sb.toString();
}catch(Exception e){Log.e("log_tag", "Error converting result "+e.toString());}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
results.add((String) json_data.get("Messdaten") + " "+ json_data.get("Wert") + " " + json_data.get("Einheit"));
}
fillList();
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
public void fillList() {
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
}
}
The setListAdapter is not working in a FragmentActivity anymore
setListAdapter() is a method on ListActivity or ListFragment. You call setAdapter() on your ListView in other cases, such as this one.
Also, please get rid of your StrictMode stuff and fix your app to move your I/O into a background thread.
I just build a demo application through async task and now i want the json data in list view so i dont know where i can add json functions and array list etc so plz guide me or help me by edit the code i thankful in advance and plz help im new to android and java
package your.packag.namespace;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class runActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}}
You can use the built-in org.json classes to convert the retrieved string (your text variable content) in to JSON objects.
Have a look at the tutorial from Lars Vogel on how to do that.