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>
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>
i am trying to implement sample JSON data App that Gets JSON data from server
i am Getting complete JSON file whats wrong with my coding ?
i am following an youtube tutorial but he did successfully but i am getting complete JSON File
this is JSON server side file
{
"movies" :[
{
"movie" : "Avenger",
"year" : 2012
}
]
}
and this is code from android app
package com.yog.jsonparser;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;
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.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView)findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://myDomainName.com/getData.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpURLConnection connection = null;
BufferedReader reader = null;
URI url;
StringBuffer buffer;
#Override
protected String doInBackground(String... params){
try{
//URL OF REQUESTED PAGE
url=new URI(params[0]);
connection = (HttpURLConnection) (new URL(params[0]).openConnection());
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
buffer=new StringBuffer();
String line;
while((line =reader.readLine())!=null){
buffer.append(line);
}
String finalJSON=buffer.toString();
JSONObject parentOject = new JSONObject(finalJSON);
JSONArray parentArray = parentOject.getJSONArray("movies");
JSONObject finalObject= parentArray.getJSONObject(0);
String movieName= finalObject.getString("movie");
int year=finalObject.getInt("year");
return movieName + "-" + year;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null){
connection.disconnect();
}
try{
if(reader !=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(buffer.toString());
}
}
}
current Output :
{"movies" :[{ "movie" : "Avenger","year" : 2012}]}
Expected output :
Avenger
2012
Change your onPostExecute method as below.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(s);
}
Here s will be return statement of doInBackground. "movieName + "-" + year;"
You are getting {"movies" :[{ "movie" : "Avenger","year" : 2012}]} in the TextView because you are setting the buffer's output to the TextView. Change your onPostExecute like this:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null){
tvData.setText(s);
}else{
//// Some error occurred
tvData.setText(buffer.toString());
}
}
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);
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.