package com.android.housingapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.housingapp.helper.JSONParser;
import com.android.housingapp.helper.ListViewAdapter;
import com.android.housingapp.helper.ListViewAdapterComplaints;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class BillsandDuesSpinner extends Activity{
Button btnaddyear,btnnext;
String name_array[];
Spinner yearspinner, spmonth;
String year_id,year,month,own_id;
String url;
JSONParser jParser ;
JSONArray montharray= null;
Context context=this;
int success=0;
JSONObject json;
ArrayList<HashMap<String, String>> monthList;
List<NameValuePair> params = new ArrayList<NameValuePair>();
ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static final String TAG_DUE_MAIN= "all_year_list";
private static final String TAG_DUE_ID = "year_id";
private static final String TAG_DUE_MON = "month";
private static final String TAG_DUE_YEAR = "year";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.billsandduesspinner);
btnaddyear=(Button)findViewById(R.id.btnaddyear);
btnnext=(Button)findViewById(R.id.btnnext);
yearspinner=(Spinner)findViewById(R.id.spyear);
spmonth=(Spinner)findViewById(R.id.spmonth);
own_id=getIntent().getExtras().getString("own_id");
monthList =new ArrayList<HashMap<String, String>>();
new BindYear().execute();
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.month,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spmonth.setAdapter(adapter);
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
btnaddyear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),NewYear.class);
startActivity(i);
}
});
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(BillsandDuesSpinner.this,TypesofBills.class);
startActivity(i);
}
});
}
class BindYear extends AsyncTask<String,String,String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsandDuesSpinner.this);
pDialog.setMessage("Loading complains. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// contactList = new ArrayList<HashMap<String, String>>()
// Creating JSON Parser instance
jParser = new JSONParser();
// getting JSON string from URL
try {
json = jParser.getJSONFromUrl(url);
if(json.has(TAG_DUE_MAIN))
{
// Getting Array of Contacts
montharray = json.getJSONArray(TAG_DUE_MAIN);
name_array = new String[montharray.length()];
// looping through All Contacts
for(int i = 0; i < montharray.length(); i++){
JSONObject c = montharray.getJSONObject(i);
// Storing each json item in variable
year_id=c.getString(TAG_DUE_ID);
month = c.getString(TAG_DUE_MON);
year = c.getString(TAG_DUE_YEAR);
name_array[i] = c.getString(TAG_DUE_YEAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DUE_ID,year_id );
map.put(TAG_DUE_MON,month);
map.put(TAG_DUE_YEAR,year );
// adding HashList to ArrayList
monthList.add(map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// Pass the results into ListViewAdapter.java
try{
if(json.has(TAG_DUE_MAIN))
{
ArrayAdapter<String> adapter = new ArrayAdapter<String> (BillsandDuesSpinner.this, android.R.layout.simple_spinner_item, name_array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yearspinner.setAdapter(adapter);
}
else{
Toast.makeText(BillsandDuesSpinner.this,"No year is available now.Please add one.",Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
e.printStackTrace();
}
pDialog.dismiss();
}
}
}
Here is a simple code of binding json data in a spinner.My php code for fetching json data is absolutely alright.The problem is whenever I try to bind json data in the spinner,at first the app crashes(showing null pointer exception) or it bind nothing into the spinner.But when I again click the button which will bind the json data into the spinner (it resides into another activity), after crashing(not running the app again),then the data is binded to the spinner sucessfully.So what is the problem??why the data is not binding at the first time??
Try this..
Initialize the url before calling BindYear BindYear
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
new BindYear().execute();
Because at the first time url is empty. That time you will get Exception in doInBackground os json is null then onPostExecute will run that time you are accessing from json as json.has that time you will get NPE
as #Hariharan answered that is the porblem you are getting NPE for first time.So the best approach would be as follows,
url="http://10.0.2.2:80/Android/HousingApp/get_due_mon_spinner.php";
new BindYear().execute(url);
and in doInBackground() change as follows,
json = jParser.getJSONFromUrl(params[0]);
Related
I have searched, but haven't been able to find a proper solution for my problem.
I am receiving data from a server and displaying it, I want this data to be stored locally, preferably in SharedPreferences or a file
If there is Internet access, the data should be stored and updated.
If there is no Internet access this data should be displayed.
Below is my code
package com.timetable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
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;
public class MondayTimeTable_TE_Elex extends ListActivity {
// JSON Node names
private static String TAG_ID = "id";
private static String TAG_NAME = "name";
String FILENAME = "monday_te_elex_file";
FileInputStream fis;
ListView listViewItem;
// contacts JSONArray
JSONArray monday_te_elex = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monday_time_table_te_elex);
new PlaceOrder().execute();
listViewItem = getListView();
}
ArrayList<HashMap<String, String>> categoriesList;
class PlaceOrder extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
InputStream inputStream = null;
String result = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// Example for param :
// nameValuePairs.add(new BasicNameValuePair("id", 1));
inputStream = Request.setHttpRequest(
"http://asimmerchant.hostoi.com/TE/Elex/Monday/monday_te_elex.php",
nameValuePairs);
// Hashmap for ListView
categoriesList = new ArrayList<HashMap<String, String>>();
if (inputStream != null) {
result = StringResponse.convertResponseToString(inputStream);
result = result.trim();
}
if (result == null || result.equals("null")) {
System.out.println("Invalid request");
} else {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
try {
String id = json_data.getString(TAG_ID);
String name = json_data.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
categoriesList.add(map);
} catch (ParseException e) {
e.printStackTrace();
}
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "ERROR", Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG)
.show();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MondayTimeTable_TE_Elex.this,
categoriesList, R.layout.list, new String[] { TAG_NAME},
new int[] { R.id.name });
setListAdapter(adapter);
/**
* Selecting single ListView item
*/
}
}
}
SharedPreferences can't store only primitive type, so you can't use it to store a Collection. You could use serialization to write it on your internal storage, but it can get tricky. I would suggest you to store the JSONObject/JSONArray (result is your case) in the SharedPreferences as String.
According to me there are two ways to achieve it.
if you want to store a particular object.
You need to convert your object into string format and write it into plain text file and read later.That is even faster from reading Json.
You can serialize the object into JSON/Strings form and use sharedPreferences to store it.you can use Gson library for it.
G'day guys!
I'm trying to work out a good approach to download pictures and update a user list with the picture once it has finished downloading.
So I'm trying to create a list of user profiles in an android app, where it displays their username and a little picture at the side of them. I've been watching tutorials for the last 2 weeks and slowly getting a feel for all thing android, and I have my app pulling data down from my SQL (via PHP) server without issue, BUT I'm having trouble working out how and where I can launch an asynchronous task to download a picture for each username.
I'm thinking something along the lines of flow like this
User clicks refresh button to
App talks to PHP on webserver and pulls down list of users (does this correctly so far)
Parse all the data from the server that it got and turn it into a list (does this correctly so far)
Data in the list contains URL for profile picture (does this correctly)
Go through each list element one by one and begin async task to download picture (don't know how to go element by element to extract URL from list)
Once picture is downloaded then display it (as above, don't know how to update each element)
The behavior is sort of inspired off the "Reddit is Fun" app, whereby all the articles are displayed and preview images are loaded and displayed as they are downloaded. You see a little spinning circle as a placeholder until the image is seen.
package com.example.administrator.hellopants;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class UserlistActivity extends Activity{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> allUserList;
private static String url_all_users = "http://myurl.com/php/db_list_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERLIST = "userlist";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
JSONArray userlist = null;
Button buttonRefresh;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_userlist);
allUserList = new ArrayList<HashMap<String,String>>();
buttonRefresh = (Button) findViewById(R.id.button_refresh);
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new PopulateUserList().execute();
}
});
}
class PopulateUserList extends AsyncTask<String, String, String> {
ListView lvItems = (ListView) findViewById(R.id.listview_usernames);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserlistActivity.this);
pDialog.setMessage("Loading users details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
Log.d("All Usernames JSON Output: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userlist = json.getJSONArray(TAG_USERLIST);
// looping through All Products
for (int i = 0; i < userlist.length(); i++) {
JSONObject c = userlist.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_USERNAME, name);
// adding HashList to ArrayList
allUserList.add(map);
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
UserlistActivity.this, allUserList,
R.layout.list_userliststyle, new String[] { TAG_ID,
TAG_USERNAME},
new int[] { R.id.list_userliststyle_id, R.id.list_userliststyle_username });
// updating listview
lvItems.setAdapter(adapter);
}
});
}
}
public class DownloadImageBackground extends AsyncTask<String, Void, Drawable> {
ImageView imageView;
String myURL = null;
#Override
protected Drawable doInBackground(String...strings) {
this.myURL = strings[0];
Log.i("doInBackground", "Loading image from: "+ myURL.toString());
//TODO: Pass the correct URL to download_image
return download_Image(myURL);
}
#Override
protected void onPostExecute(Drawable result) {
imageView.setImageDrawable(result);
}
private Drawable download_Image(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, url);
return d;
} catch (Exception e) {
Log.e("download_Image", "Caught exception: "+e.getMessage());
return null;
}
}
}
}
Okie thanks to Nasch, that seemed to help prod me in the right direction
String username = allUserList.get(0).get(TAG_USERNAME);
Log.d("And the winner is", username);
And thus the username string is printed out. To do that with a URL is probably similar, but my main problem was trying to work out how to pull data out from the list and that seems to have been solved now :D (finally after 3 days, phew)
Had a feeling it would be something simple that I couldn't figure out.
Ok i've written this android program that has 3 tabs(MEALS,DRINKS AND DESSERT) each in its own activity with a fragment.The problem i'm having now is with retrieving the list from a mysql database and displaying this list in each tab.I'de already ran and executed a custom code which displays a list of items retrieved from a mysql database in a single list,which worked fine.Now bringing this code to my program gives me 3 errors
1)
pDialog = new ProgressDialog(MealsFragment.this); which says
ProgressDialog(android.context,Context) in progressDialog cannot be applied to
com.example.tab.tablayout.MealsFragment
2)
runOnUiThread(new Runnable() which says "cannot resolve method runonuithread "
3)is all about the list adapter.
The initial code used OnCreate,but my fragment uses oncreateView.I dont know if thats the issue.
Here is the code for the MealsFragment.java
package com.example.tabs.tablayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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;
/**
* Created by GIGABYTE on 5/21/2014.
*/
public class MealsFragment extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> mealsList;
// url to get all products list
private static String url_all_meals = "http://10.180.79.73/dbase_connect/get_all_meals.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MEALS = "meals";
private static final String TAG_MID = "mid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray meals = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_meals, container, false);
// Hashmap for ListView
mealsList = new ArrayList<HashMap<String, String>>();
// Loading meals in Background Thread
new LoadAllMeals().execute();
// Get listview
ListView lv = getListView();
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllMeals extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MealsFragment.this);
pDialog.setMessage("Loading Meals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All Meals from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_meals, "GET", params);
// Check your log cat for JSON response
Log.d("All Meals: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Meals found
// Getting Array of Meals
meals = json.getJSONArray(TAG_MEALS);
// looping through All meals
for (int i = 0; i < meals.length(); i++) {
JSONObject c = meals.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_MID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mealsList.add(map);
}
} /*else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
*/
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all meals
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MealsFragment.this, mealsList,
R.layout.meals_list_item, new String[] {TAG_MID,
TAG_NAME},
new int[] { R.id.mid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
1) The first parameter of the ProgressDialog constructor must be a context. Use
new ProgressDialog(getActivity());
2) You could use getActivity().runOnUiThread(...). However, that's not necessary in this context. The AsyncTask.onPostExecute() method is already running in the UI thread. Just move the Runnable code into the body of the onPostExecute() method.
3) Same as 1, first parameter must be a context. Use new SimpleAdapter(getActivity(), ...).
my asynctask is not working. The dialog wont dismiss and the list is not being updated (i think because onPostExecute is not being called).I googled it, but without result.
package com.example.whs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
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;
public class Albums extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// Array for the list
ArrayList<HashMap<String, String>> itemList;
// url to get the items
private static String url_all_products = "<my url here>";
// JSON variables
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ITEMS = "items";
private static final String TAG_NAME = "name";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
//JSON array
JSONArray items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
// HashMap for the items
itemList = new ArrayList<HashMap<String, String>>();
// Loading the items on the background
new LoadAllItems().execute();
// Get list-view
ListView lv = getListView();
// On item click
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//do
}
});
}
// class for loading all items
class LoadAllItems extends AsyncTask<String, String, String> {
// Before
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Albums.this);
pDialog.setMessage("Albums laden...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Get the products
#Override
protected String doInBackground(String... params) {
// Build Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
//Get the JSON string
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params1);
// Check for response
Log.d("All Items: ", json.toString());
try {
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
// found the items
items = json.getJSONArray(TAG_ITEMS);
// loop through the items
for (int i = 0; items.length() > i; i++){
// Get the item in variable c
JSONObject c = items.getJSONObject(i);
// Store in a variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String username = c.getString(TAG_USERNAME);
if(username == ""){
username = "onbekend";
}
// Create the HashMap
HashMap<String, String> map = new HashMap<String, String>();
// add it
map.put(TAG_ID, id);
map.put(TAG_USERNAME, username);
map.put(TAG_NAME, name);
// to arraylist
itemList.add(map);
}
}else{
// nothing found
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result){
// dismiss dialog
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
// Add adapter to the list
MenuAdapter adapter = new MenuAdapter(Albums.this, itemList);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.albums, menu);
return true;
}
}
the loop is working correctly.
How to fix this?
1) you are trying to start an activity within the background thread, don't do this.
2) you are probably getting a json exception, just log more things so you can see what is happening
these may be why it never reaches onPostExecute
you can not perform UI related action in doInBackGround(), like you are strating a new activity in doInBaclground,
Intent i = new Intent(getApplicationContext(), Index.class);
// close the previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
I have an app that uses Zxing barcode scanner to scan inventory assets (computers, equipment)
I can return the barcode into a text field. I then can enter more data for that particular scanned asset in other Edit text fields on the form(description, model, serial#). There are buttons down below for saving data to my SQLite DB in a ListView in another activity. I want to know, if I can click on one of the items in the list view and have it's contents sent to mysql server. I've seem some info on the web (google), but does anyone know any good tutorials or walk throughs that can guide me.
Thanks,
To achieve this, you would generally run a web service that accepts the data from your app and inserts it into the MySQL database. You could write the web service in any server-side scripting language, but most examples make use of PHP.
For more information, I would suggest looking at these similar questions:
How to connect to a remote MySQL DB without webservices... ? (ANDROID)
Android remote MySQL operations using a web service with php
Perhaps you would find Kumulos of interest, it's a tool I've been involved in building that allows you to create these kinds of web service and integrate them into your mobile apps.
I was able to do this by passing the selected item to onItemClick based on some code i found online, hope this helps anyone still trying to solve this
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.henga.beverage.JSONParser;
public class Songs extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(Songs.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Songs.this, oslist,
R.layout.list_songs,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(oslist.get(+position).get("name"));
Toast.makeText(Songs.this, "You Clicked on "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
startActivity(new Intent(Songs.this, Main.class));
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
Toast.makeText(getApplicationContext(), "Vote sent", Toast.LENGTH_LONG).show();
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/z/receiver.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
#SuppressWarnings("unused")
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}