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.
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>
As title suggests, here is the format of the JSON:
http://prntscr.com/elb4fz. Now I'm not sure if I have the parse method working properly as I think that SearchResults is the array and it'll show each individual result as an object.
I have my networkutils code as such:
package companionsdirect.practice;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Albedo on 3/17/2017.
*/
public class NetworkingUtil {
private static final String TAG = "NetworkUtils";
List<Product> items = new ArrayList<>();
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " + urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public List<Product> fetchItems(String url) {
try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} catch (IOException ioe) {
Log.i(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}
return items;
}
public List<Product> getProdList() {
return items;
}
private void parseItems(List<Product> items, JSONObject jsonBody) throws IOException, JSONException {
//JSONObject reviewItem = jsonBody.getJSONObject();
JSONArray reviewArray = jsonBody.getJSONArray("SearchResults");
for(int i = 0;i<reviewArray.length();i++) {
JSONObject reviewItem = reviewArray.getJSONObject(i);
Product currentProductReview = new Product();
currentProductReview.setmSummary(reviewItem.getString("Summary"));
currentProductReview.setmTitle(reviewItem.getString("Title"));
currentProductReview.setmRecordType(reviewItem.getString("RecordType"));
items.add(currentProductReview);
}
}
}
And this is the activity with the asynctask:
package companionsdirect.practice;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ReturnReviewsActivity extends AppCompatActivity {
public String builtURL;
List<Product> prodList;
private static final String TAG = "ReturnReviewsActivity";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_reviews);
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.EXTRA_MSG);
prodList = new ArrayList<Product>();
builtURL = url;
new FetchItemsTask().execute();
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
tv.setText(x.getmTitle() + " " + x.getRating() + " \n");
}
}
private class FetchItemsTask extends AsyncTask<Void, Void, Void> {
private List<Product> list;
#Override
protected Void doInBackground(Void... params) {
NetworkingUtil productData = new NetworkingUtil();
list = productData.fetchItems(builtURL);
return null;
}
}
}
What gives? The log shows that the json is being received,but I try to set the textview to whatever is in the list and nothing shows.
Try this
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
//append the text view
tv.append(x.getmTitle() + " " + x.getRating() + " \n");
}
I have this code that I am trying to run after making all kinds of changes to it. The problem is that i have added permissions and added still find that the code seems to be not working.
It would be a great help if anyone can help me find my mistake.
Where am I going wrong.
This is the .java file.
package com.example.adityapc.phpfeeddisplay;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
public class ActivityMain extends Activity {
private static final String TAG = "Http Connection";
private ListView listAct = null;
private ArrayAdapter arrayAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listAct = (ListView) findViewById(R.id.listActivity);
final String url = "http://anonymoous.marshalcadetacademy.com/notification.php";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
Integer result = 0;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
parseResult(response);
result = 1;
}else{
result = 0;
}
}
catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
if(result == 1){
arrayAdapter = new ArrayAdapter(ActivityMain.this, android.R.layout.simple_list_item_1,R.id.listActivity);
listAct.setAdapter(arrayAdapter);
}
else{
Log.e(TAG, "Failed to fetch data!");
}
}
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null){
result += line;
}
if(null!=inputStream){
inputStream.close();
}
return result;
}
private void parseResult(String result) {
try{
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
String[] blogTitles = new String[posts.length()];
for(int i=0; i< posts.length();i++ ){
JSONObject post = posts.optJSONObject(i);
String title = post.optString("title");
blogTitles[i] = title;
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
And here is the .xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:id="#+id/linear" >
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/listActivity"
android:layout_gravity="center">
</ListView>
</LinearLayout>
If you all have any suggestions to make, your help will be appreciated.
I am a newbie to Android development, and I have encountered a halt in my application development. I hope somebody can help me out here.
I have an activity named JSONActivity and inside JSONActivity, I extract JSON data from a web url, and store it into 3 HashMaps, depending on the type of data.
I would like to pass a HashMap to 3 different Fragments. I'll start with just doing it for one fragment however, I cannot seem to pass the data.
Can somebody point out what I am doing wrong, and what I can do to fix it?
I can assure that the json extraction works fine, because the data can be rendered using a Toast
JSONActivity.java
package com.example.json;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import android.app.Activity;
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.StatusLine;
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.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.os.AsyncTask;
public class JSONActivity extends Activity {
HashMap<Integer,String> imageList = new HashMap<Integer,String>();
HashMap<Integer,String> textList = new HashMap<Integer,String>();
HashMap<Integer,String> otherList = new HashMap<Integer,String>();
private static final String ID = "id";
private static final String TYPE = "type";
private static final String DATA = "data";
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of json items: " +
jsonArray.length());
//---print out the content of the json feed---
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt(ID);
String type = jsonObject.getString(TYPE);
String data = jsonObject.getString(DATA);
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);
// Toast.makeText(getBaseContext(), jsonObject.getString("type") +
// " - " + jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ReadJSONFeedTask().execute(
"sample url (not shown in this post)");
}
}
Fragment1.java:
package com.example.json;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class fragment1 extends ListFragment {
#SuppressWarnings("unchecked")
public HashMap<Integer,String> textList =
(HashMap<Integer, String>) getArguments().getSerializable("textList");
public String[] vals = new String[textList.size()];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)textList.values().toArray()[i];
return inflater.inflate(R.layout.fragment1, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(getActivity(),
"You have selected " + vals[position], Toast.LENGTH_SHORT).show();
}
}
fragment1.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="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
main.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="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_weight="0.5" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="300dp"
android:layout_weight="0.5" />
</LinearLayout>
You need to define a setter method in your fragments which will set the HashMap property of fragment and display it to the user. After that when you done parsing json data call it like this:
((Fragment1) getSupportFragmentManager.findFragmentById(R.id.fragment1)).setAndDisplayJSONDataMethod(valuesToShow);
and setAndDisplayJSONDataMethod method will be something like this:
public void setAndDisplayJSONDataMethod(HashMap<Integer, String> valuesToShow) {
String[] vals = new String[textList.size()];
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)valuesToShow.values().toArray()[i];
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
For now it doesn't work cause you're trying to get/set your list data in a wrong place and in a wrong time. Read about Fragments and Fragments/Actvities lifecycles.
In java, strings have to be compared with equals or equalsIgnoreCase
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);
i am new in android. I managed to parse JSON file to my application. Now i want to use AsyncTask to get Spinning progressBa untill application starts and load data. I tried to read many things, but they only give how to get progressbar on onclick events or for downloading events.
This is my code...
I just confused about how to start progressbar at starting of your application and which part of following code goes to which method of asycTask class....
package com.demojson;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
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.TextView;
import android.widget.Toast;
import android.app.ListActivity;
public class MainActivity extends ListActivity {
private static String url = "http://timepasssms.com/webservices/ws.php?type=category";
private static final String TAG_DATA = "DATA";
private static final String TAG_0 = "0";
private static final String TAG_ID = "id";
private static final String TAG_1 = "1";
private static final String TAG_NAME = "name";
private static final String TAG_2 = "2";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_3 = "3";
private static final String TAG_NEW_NAME = "new_name";
private static final String TAG_4 = "4";
private static final String TAG_STATUS = "status";
JSONArray jArray = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> contents = new ArrayList<HashMap<String, String>>();
JSONMethod metObj = new JSONMethod();
JSONObject jOb = metObj.getUrl(url);
try {
jArray = jOb.getJSONArray(TAG_DATA);
for (int i = 0; i < jArray.length(); i++) {
JSONObject child = jArray.getJSONObject(i);
String tag_0 = child.getString(TAG_0);
String id = child.getString(TAG_ID);
String tag_1 = child.getString(TAG_1);
String name = child.getString(TAG_NAME);
String tag_2 = child.getString(TAG_2);
String description = child.getString(TAG_DESCRIPTION);
String tag_3 = child.getString(TAG_3);
String new_name = child.getString(TAG_NEW_NAME);
String tag_4 = child.getString(TAG_4);
String status = child.getString(TAG_STATUS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME , name);
contents.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contents,
R.layout.list_items, new String[] { TAG_NAME },
new int[] { R.id.tvName });
setListAdapter(adapter);
// --To get listview set...--
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view.findViewById(R.id.tvName)).getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), item , Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}
and JSONMethod Class...
package com.demojson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.util.Log;
public class JSONMethod {
InputStream is = null;
JSONObject jObj=null;
String json = "";
public JSONObject getUrl(String url){
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpRespone = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespone.getEntity();
is = httpEntity.getContent();
}catch(UnsupportedEncodingException ue){
}catch(ClientProtocolException ce){
}catch(IOException ie){
}
try{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line=null;
while((line=br.readLine())!= null){
sb.append(line + "/n");
}
is.close();
json = sb.toString();
}catch(Exception e){
Log.e("JSONMethod", "Error converting result" + e.toString());
}
try{
jObj = new JSONObject(json);
}catch(Exception e){
Log.e("JSONMethod", "Error parsing data" + e.toString());
}
return jObj;
}
}
here is xml files...
activity_main.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="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:src="#drawable/timepasssms" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
</LinearLayout>
and list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/round_edge"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:layout_marginLeft="10dp"
android:gravity="left"
android:padding="5dp"
android:textColor="#DF7401"
android:textSize="20dp" />
</LinearLayout>
here is example `
#Override
protected void onPostExecute(Object table) {
// TODO Auto-generated method stub
super.onPostExecute(table);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=ProgressDialog.show(Yourclass.this, "Loading Data.", "Please Wait");
}
`
I hope would be helpful
Try Using Async class and in doInBackground() method load your List view.
This is how to call Async Class
new LoadListView(this).execute(listView);
And here is your Async Class
public class LoadListView extends AsyncTask<ListView> {
private Context context;
public loadListView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected String doInBackground(String... aurl) {
//Here you need to load your ListView
return null;
}
protected void onProgressUpdate(String... progress) {
//Show progress bar here
}
#Override
protected void onPostExecute(String unused) {
//Hide Progress Bar Here
}
It will automatically hide progress bar when listview is loaded..