Asynctask: pass values from doInBackground to onPostExecute - java

I´m new in Java programming and have a question. I found this post and tried to use this method to pass my values from doInBackground method to onPostExecute method. But Android Studio 2.3 does not allow it.
Android Studio underline my #Override at onPostExecute:
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create adapter for ListView (Universal Image Loader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
and my QueryResult in doInBackground:
#Override
protected QueryResult doInBackground(String... params){
try
{
Here is all the code:
public class MultiplyTask extends AsyncTask<String,Void,ArrayList<Artikel>>{
private class QueryResult {
ArrayList<Artikel> dataList;
public QueryResult(ArrayList<Artikel> dataList) {
this.dataList = dataList ;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected void onPostExecute(String s){
//super.onPreExecute();
// Create Adapter for ListView (UniversalImageLoader)
AngeboteListAdapter adapter = new AngeboteListAdapter(this, R.layout.angebote_list_view_adapter, dataList);
mListView.setAdapter(adapter);
Toast.makeText(AngeboteActivity.this,"onPostExecute",Toast.LENGTH_LONG).show();
}
String data ="";
#Override
protected QueryResult doInBackground(String... params){
try
{
URL url = new URL("https://myjson.com");
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;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][5];
//Fill Array with response
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("Artikelnummer"));
matrix[i][1] = String.valueOf(obj.getDouble("Preis"));
matrix[i][2] = obj.getString("Von");
matrix[i][3] = obj.getString("Bis");
matrix[i][4] = obj.getString("art_link");
}
//new Arrays
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
//Array sort
for (int i = 0; i < matrix.length; i++) {
all_art_nr[i] = matrix[i][0];
all_preis[i] = matrix[i][1];
all_von[i] = matrix[i][2];
all_bis[i] = matrix[i][3];
all_link[i] = matrix[i][4];
}
//Fill Arraylist
ArrayList<Artikel> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
Artikel angebote = new Artikel(all_art_nr[i], all_preis[i], all_von[i], all_bis[i], all_link[i]);
dataList.add(angebote);
}
return new QueryResult(dataList);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Android Studio want to change QueryResult into Arraylist and the #Override does not override method from his superclass, if i take QueryResult in doINBackground out, he can override the superclass method. Thanks in advance.

When you extends the Asynctask check the parameter:
extends Asynctask<Params, Progress, Result>
So if you want to pass a String to your doInBackround which will return a QueryResult to your onPostExecute you should extends like this:
extends Asynctask<String, Void, QueryResult>

Related

Need help to retrieve all the data to listview

I'm trying to make an android application that can read data from a database. but when I try to display some rows in the listview, only the bottom row of the code that I make is displayed.
this is my code for MainActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
getJSON("http://192.168.137.234/librenms/getdata.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) !=null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] alerts = new String[jsonArray.length()];
this is the part to showing the atribute on listview
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
alerts[i] = object.getString("Rule ID");
alerts[i] = object.getString("Device ID");
alerts[i] = object.getString("Time logged");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, alerts);
listView.setAdapter(arrayAdapter);
}
}

Inquire variable in other class / activity if it is filled

I am beginner in Java and Android. I searched yesterday a whole day for a solution. I want to check a variable in second activity if it is filled. Or ask the methode "loadAngebote" if it has a return value. The methode that is executed to get data is:
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/file.php");
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;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
return dataList; <--------------------------------------------
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
I need to check if dataList is filled in an other class of my app:
static String getLocationResultTitle(Context context, List<Location> locations) {
if(?????dataList_is_filled?????){
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
Updated Answer
Here is your AngeboteActivity
public class AngeboteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>> {
String data = "";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params) {
try {
URL url = new URL("http://url/file.php");
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;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i = 0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €", "Von: " + all_von[i], "Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult) {
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
}
And Here is your Utils class
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}
Ok now Your Activity looks good..
Now in Utils class change if(loadAngebote.DataHolder.hasData()) to if (AngeboteActivity.DataHolder.hasData())
Here:-
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}
UPDATED ANSWER My Angebote Activity:
public class AngeboteActivity extends AppCompatActivity {
public static TextView data;
public static ListView mListView;
private static final String TAG = "AngeboteActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_angebote);
data = (TextView) findViewById(R.id.data);
mListView = (ListView) findViewById(R.id.listView);
new loadAngebote().execute();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object Inhalt = parent.getAdapter().getItem(position);
final Intent intent = new Intent(AngeboteActivity.this, AngeboteRequestInfoActivity.class);
Bundle bundle = new Bundle();
//Objekt Serialisieren
bundle.putSerializable("object", (Serializable) Inhalt);
//Objekt in Intent Extras packen
intent.putExtras(bundle);
AngeboteActivity.this.startActivity(intent);
}
});
}
private class QueryResult {
ArrayList<ArtikelAngebot> dataList;
public QueryResult(ArrayList<ArtikelAngebot> dataList) {
this.dataList = dataList ;
}
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/request.php");
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;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
My Utils.java class
public class Utils {
final static String KEY_LOCATION_UPDATES_REQUESTED = "location-updates-requested";
final static String KEY_LOCATION_UPDATES_RESULT = "location-update-result";
static void setRequestingLocationUpdates(Context context, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_LOCATION_UPDATES_REQUESTED, value)
.apply();
}
static boolean getRequestingLocationUpdates(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_LOCATION_UPDATES_REQUESTED, false);
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
static void sendNotification(Context context, String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(context, AngeboteActivity.class);
notificationIntent.putExtra("from_notification", true);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(AngeboteActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
// Notification Einstellungen
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle("Ihre Apotheke vor Ort")
.setContentText(notificationDetails)
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Returns the title for reporting about a list of {#link Location} objects.
*
* #param context The {#link Context}.
*/
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
/**
* Returns te text for reporting about a list of {#link Location} objects.
*
* #param locations List of {#link Location}s.
*/
private static String getLocationResultText(Context context, List<Location> locations) {
if (locations.isEmpty()) {
return "Unbekannte Position";
}
StringBuilder sb = new StringBuilder();
for (Location location : locations) {
sb.append("(");
sb.append(location.getLatitude());
sb.append(", ");
sb.append(location.getLongitude());
sb.append(")");
sb.append("\n");
}
return sb.toString();
}
static void setLocationUpdatesResult(Context context, List<Location> locations) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(KEY_LOCATION_UPDATES_RESULT, getLocationResultTitle(context, locations)
+ "\n" + getLocationResultText(context, locations))
.apply();
}
static String getLocationUpdatesResult(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY_LOCATION_UPDATES_RESULT, "");
}
}

Parsing multiple JsonObject and JsonArray

I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}

how to get listview data from parseJson

hi please answer my question
i have this code in eclipse for Android Developing.
i am using mysql and php for database and get data with JSON . But i dont know how can i use JSONparse data in listview . please edit my codes.
public class ViewAllPersons extends Activity {
String url = "http://192.168.1.206/androhp/view_all_persons.php";
ArrayList<String> result;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_person);
result = new ArrayList<String>();
LoadAllPersons lap = new LoadAllPersons();
lap.execute(url);
}
class LoadAllPersons extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
InputStream jsonStream = getStreamFromURL(args[0], "GET");
String jsonString = streamToString(jsonStream);
parseJSON(jsonString);
return null;
}
void parseJSON(String JSONString) {
try {
JSONObject jo = new JSONObject(JSONString);
JSONArray allpersons = jo.getJSONArray("allpersons");
for (int i = 0; i < allpersons.length(); i++) {
JSONObject object = allpersons.getJSONObject(i);
String objString = "";
objString = object.getString("name") + " , "
+ object.getString("name2") + " : "
+ object.getInt("iconlink");
result.add(objString);
}
} catch (JSONException e) {
}
}
protected void onPostExecute(String file_url) {
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
CustomList adapter = new
CustomList(ViewAllPersons.this, web, imageUrl);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
How can I use parseJSON data instead of web listview :
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
You have got both data as well as list, now you need to combine them.
first you have to convert your json result into list, where values are your json values.
final ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listdata .add(values[i]);
}
then you have to assign adapter to your list. You can use following code.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.yourlistlayout, listdata );
list.setAdapter(adapter);
More details
http://www.vogella.com/tutorials/AndroidListView/article.html

changing interface in an asynctask (the right way)

I'm trying to change the process data retrieved into a list view. The data is recieved properly. but i'm failing to make up the list view the right way.
Here is my asynctask class
class GetFriendsInfo extends AsyncTask<String, String, String>{
String id = "";
String fullName = "";
String birthday = "";
protected void onPreExecute() {
super.onPreExecute();
pd_GetData = new ProgressDialog(MainActivity.this);
pd_GetData.setMessage("Getting friend data");
pd_GetData.setIndeterminate(false);
pd_GetData.setCancelable(true);
pd_GetData.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray friendArray;
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_id", id));
param.add(new BasicNameValuePair("user_id", fullName));
param.add(new BasicNameValuePair("user_id", birthday));
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
try{
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1){
Log.d("PHP Server [GET]", "Retrieved user data");
String jsonString = jsonObject.getString("message");
friendArray = new JSONArray(jsonString);
String[] names = new String[friendArray.length()];
String[] birthdays = new String[friendArray.length()];
String[] ids = new String[friendArray.length()];
for(int i=0; i<friendArray.length(); i++) {
JSONObject friend = friendArray.getJSONObject(i);
String friend_id = friend.getString("id");
ids[i] = friend_id;
String friend_name = friend.getString("fullName");
names[i] = friend_name;
String friend_birthday = friend.getString("birthday");
birthdays[i] = friend_birthday;
}
Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));
List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>();
for (int i=0;i<names.length;i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("names", names[i]);
hm.put("ids", ids[i]);
hm.put("birthdays", birthdays[i]);
birthday.add(hm);
}
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}else{
Log.d("PHP Server [GET]", "Failed retrieve user data");
}
}catch (JSONException e){
e.printStackTrace();
}catch (RuntimeException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pd_GetData.dismiss();
}
}
I know that i shouldn't create the listview in the doInBackground. But i don't have a clue how i should do it.
This should give you the idea. Read the inline comments:
class GetFriendsInfo extends AsyncTask<Void, Void, JSONObject> {
private String url;
public GetFriendsInfo(String url_get_birthdays) {
this.url = url_get_birthdays;
}
#Override
protected JSONObject doInBackground(Void... params) {
// Make your network call and get your JSONObject
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
// Here you get your jsonObject on the main thread. You can parse it and update your UI
// Convert your jsonObject to what you want and then show the dialog
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}
}
set your adapter in onPostExecute() method.
class GetFriendsInfo extends AsyncTask<String, String, String>{
String id = "";
String fullName = "";
String birthday = "";
List<HashMap<String, String>> birthday;
protected void onPreExecute() {
super.onPreExecute();
pd_GetData = new ProgressDialog(MainActivity.this);
pd_GetData.setMessage("Getting friend data");
pd_GetData.setIndeterminate(false);
pd_GetData.setCancelable(true);
pd_GetData.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray friendArray;
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_id", id));
param.add(new BasicNameValuePair("user_id", fullName));
param.add(new BasicNameValuePair("user_id", birthday));
JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);
try{
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1){
Log.d("PHP Server [GET]", "Retrieved user data");
String jsonString = jsonObject.getString("message");
friendArray = new JSONArray(jsonString);
String[] names = new String[friendArray.length()];
String[] birthdays = new String[friendArray.length()];
String[] ids = new String[friendArray.length()];
for(int i=0; i<friendArray.length(); i++) {
JSONObject friend = friendArray.getJSONObject(i);
String friend_id = friend.getString("id");
ids[i] = friend_id;
String friend_name = friend.getString("fullName");
names[i] = friend_name;
String friend_birthday = friend.getString("birthday");
birthdays[i] = friend_birthday;
}
Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));
birthday = new ArrayList<HashMap<String, String>>();
for (int i=0;i<names.length;i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("names", names[i]);
hm.put("ids", ids[i]);
hm.put("birthdays", birthdays[i]);
birthday.add(hm);
}
}else{
Log.d("PHP Server [GET]", "Failed retrieve user data");
}
}catch (JSONException e){
e.printStackTrace();
}catch (RuntimeException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
pd_GetData.dismiss();
}
}
As UI operation can not be done in doinbackground. So first make birthday list global in asyntask.
List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>(); // make it Global.
move the below part from doinbackground to
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pd_GetData.dismiss();
String[] from = {"names", "ids", "birthdays"};
int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
featuredList.setAdapter(adapter);
}
If you have still nay query please let me know.

Categories

Resources