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>
Related
I want to Print My data from database In form of TableView How do I print data.
Database i used is SQLite.
Just take data from your API or service Inform of JSON and follow the below reference.
Answer ref
make a file fetchData.java
import android.os.AsyncTask;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/107msz");
HttpURLConnection httpURLConnection = (HttpURLConnection)
url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n"+
"Password:" + JO.get("password") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.dataParsed);
}
}
Another file MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button) findViewById(R.id.button);
data = (TextView) findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchData process = new fetchData();
process.execute();
}
});
}
}
In your Activity_main.xml write this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.abhishekpanwar.receivedatajson.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!"
android:layout_marginBottom="10dp"
android:id="#+id/button"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/button">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="40sp"
android:id="#+id/fetcheddata"
android:fontFamily="sans-serif"
android:hint="Fetched Text Here!!!"/>
</ScrollView>
</RelativeLayout>
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();
}
}
}
I am trying to set a textview value in a widget via an async task. I created a simple widget whose layout looks like this:
widget_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/widget_bg_normal"
>
<TextView
android:id="#+id/widget_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="testing 123"
android:layout_gravity="center_horizontal|center"
android:layout_marginTop="5dip"
android:padding="10dip"
android:textColor="#android:color/black"
>
</TextView>
</LinearLayout>
My AppWidgetProvider code is:
package com.example.beerportfoliopro;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
/**
* Created by Mike on 12/26/13.
*/
public class HelloWidget extends AppWidgetProvider {
#Override
public void onEnabled(Context context){
//build url for async task
String url = "hiddenURL";
//call async task
new GetRandomBeer(context).execute(url);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
//todo: call update code, which should be the same as onEnabled
}
}
This above code should control what happens when the app is enabled (aka when user adds the app to their home screen) and what the app should do when it updates itself based on the time set in my hello_widget-provider.xml here:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="1000"
android:initialLayout="#layout/widget_test"
>
</appwidget-provider>
For testing purposes I am not having my asynctask parse any json yet I am just trying to change the value of the text on my widget via the async task. Here is the code for my async task:
package com.example.beerportfoliopro;
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.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.beerportfolio.beerportfoliopro.R;
public class GetRandomBeer extends AsyncTask
<String, Void, String> {
Context c;
public GetRandomBeer(Context context)
{
c = context;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
Log.d("taste","Inside get taste");
//decode json here
try{
//todo: get all beer data
//todo: set text views with data
TextView breweryTitle = (TextView) ((Activity) c).findViewById(R.widget_tv);
}
catch(Exception e){
}
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
My problem right now is that right now my widget_tv is showing the error:
cannot resolve symbol widget_tv
Your TextView ID should be: R.id.widget_tv not R.widget_tv
have you called setContentView(view) in the activity class that you are passing to the asynctask before executing the asynctask? if not you should use the layout inflater to inflate the textview
((Activity) c).getLayoutInflater().inflate(R.id.widget_tv, null);
Currently I am developing an Android app containing a list view which displays links for Youtube videos. The application gets its data from the server as JSON. Now I am trying to display thumbnails for these video from this subdomain - http://img.youtube.com/vi/.
But the images don't show up in the list view.
Here is the code for the project :
1 - canticlesActivity.java
package com.shadatv.shada;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class canticlesActivity extends ListActivity {
TextView httpStuff;
HttpClient client;
JSONArray canticles;
String picpath = "http://img.youtube.com/vi/";
File sdcard = Environment.getExternalStorageDirectory();
File shadaRoot = new File(sdcard.getAbsolutePath() + "/shada_Folder");
private static final String CA_NAME = "ca_name";
private static final String CA_LINK = "ca_link";
private static final String CA_IMG = "ca_img";
private static final String URL = "http://dt-works.com/ags/shadatv/canticles/android_data";
ArrayList<HashMap<String, String>> canticlesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute();
}
public JSONArray allCanticles() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray canticles = new JSONArray(data);
return canticles;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT).show();
return null;
}
}
public void downloadImage(String fileURL) {
try {
// Toast.makeText(getBaseContext(), "baaad", Toast.LENGTH_SHORT).show();
String finlpth = "";
finlpth = picpath + fileURL + "/2.jpg";
shadaRoot.mkdirs();
URL u = new URL(finlpth);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File DownloadedFile = new File(shadaRoot, fileURL + ".jpg");
// if(!outfile.exists())
FileOutputStream f = new FileOutputStream(DownloadedFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
}
public class Read extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
canticlesList = new ArrayList<HashMap<String, String>>();
try {
canticles = allCanticles();
for (int i = 0; i < canticles.length(); i++) {
JSONObject canticle = canticles.getJSONObject(i);
String ca_name = canticle.getString(CA_NAME);
String ca_link = canticle.getString(CA_LINK);
downloadImage(ca_link);
HashMap<String, String> map = new HashMap<String, String>();
map.put(CA_NAME, ca_name);
map.put(CA_LINK, ca_link);
map.put(CA_IMG, ca_link + ".jpg");
canticlesList.add(map);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListAdapter adapter = new SimpleAdapter(canticlesActivity.this,
canticlesList,R.layout.list_item,
new String[] {CA_NAME, CA_LINK, CA_IMG},
new int[] {R.id.ca_name, R.id.ca_link, R.id.ca_img});
setListAdapter(adapter);
}
}
}
2 - list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal" >
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<ImageView
android:id="#+id/ca_img"
android:layout_width="50dip"
android:layout_height="50dip"
android:contentDescription="#string/desc"
/>
<TextView
android:id="#+id/ca_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- Name Label -->
<TextView
android:id="#+id/ca_link"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17sp"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
You can use UniversalImageLoader
it very simple for using -imageLoader.displayImage(imageUri, imageView);
Downloading images and then displaying in ListView is bad process. Because just think if you are having >100 images then it will take more time to display it.
And now optimization which i would suggest is: Implement logic for lazy loading of Images inside ListView.
Refer below examples:
Lazy List by Fedor
Universal Image Loader
ImageLoader by Novoda
In youtube JSON data ,The entire videos information will be in "entry" JSON array. You are creating same tag name for all the entires in the Hashmap.. If you give same tag for all entries then it will display last entry image. Please change the TAG NAME to "map.put(CA_IMG+i, ca_link + ".jpg");"
I hope this solution will be helpful for you.
Can anyone tell me how to change the background color or text color of each row displayed based on the data dynamically.I have modified the example/SourceCode which I got online,will paste the code below.
Change Backgroundcolor of row to Blue if magnitude > 8.5
or
Change Backgroundcolor of Text to Blue if magnitude > 8.5
Note:Color should change, Before Clicking on the list.
Thanks a lot I appreciate the help.
Main.Java
package com.pxr.tutorial.json;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.pxr.tutorial.xmltest.R;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Main extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String jString="{\"earthquakes\": [{ \"eqid\": \"c0001xgp\", \"magnitude\": 8.8, \"lng\": 142.369, \"src\": \"us\", \"datetime\": \"2011-03-11 04:46:23\", \"depth\": 24.4,\"lat\": 38.322 },{ \"eqid\": \"2007hear\",\"magnitude\": 8.4,\"lng\": 101.3815,\"src\": \"us\", \"datetime\": \"2007-09-12 09:10:26\",\"depth\": 30,\"lat\": -4.5172},{ \"eqid\": \"2007hear\",\"magnitude\": 8.5,\"lng\": 101.3815,\"src\": \"us\", \"datetime\": \"2007-09-12 09:10:26\",\"depth\": 30,\"lat\": -4.5172},{ \"eqid\": \"2007hear\",\"magnitude\": 8.6,\"lng\": 101.3815,\"src\": \"us\", \"datetime\": \"2007-09-12 09:10:26\",\"depth\": 30,\"lat\": -4.5172},{ \"eqid\": \"2007hear\",\"magnitude\": 8.7,\"lng\": 101.3815,\"src\": \"us\", \"datetime\": \"2007-09-12 09:10:26\",\"depth\": 30,\"lat\": -4.5172}]}";
// JSONObject json=JSONfunctions.getJSONfromURL(jString);
JSONObject jObject = null;
try {
jObject = new JSONObject(jString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
JSONArray earthquakes = jObject.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
SimpleAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
JSONfunctions.java
package com.pxr.tutorial.json;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
listplaceholder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
</LinearLayout>
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="7dp"
>
<TextView
android:id="#+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="2dp"
android:textSize="20dp" />
<TextView
android:id="#+id/item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="13dp" />
</LinearLayout>
You need to override the setViewBinder() method of your Adapter. Check this link.
Try the following code and let me know:
SimpleAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
int v=view.getId();
if(v==R.id.item_subtitle && Float.valueOf(data.toString())>8.5){
((View) view.getParent()).setBackgroundColor(Color.BLUE);
}
TextView TV=(TextView) view;
TV.setText(data.toString());
return true;
}
});
setListAdapter(adapter);
SimpleAdapter is for static data. If you want to optimize it you'd better off create your own custom adapter.