Parsing JSON from sdcard - GSON - android

Hi I created parsing JSON from http server based on this tutorial. But I want parse this JSON file from sdcard. I'm able to print json file location using Environment.getExternalStorageDirectory().getAbsolutePath(), But I don't know how to change the AsyncTask read the file. can someone help me to do this stuff? (I'm new to android development)
Code looks like this:
public class ClientActivity extends Activity {
TextView capitalTextView;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
capitalTextView = (TextView) findViewById(R.id.capital_textview);
this.retrieveCapitals();
}
void retrieveCapitals() {
progressDialog = ProgressDialog.show(this,
"Please wait...", "Retrieving data...", true, true);
CapitalsRetrieverAsyncTask task = new CapitalsRetrieverAsyncTask();
task.execute();
progressDialog.setOnCancelListener(new CancelListener(task));
}
private class CapitalsRetrieverAsyncTask extends AsyncTask<Void, Void, Void> {
Response response;
#Override
protected Void doInBackground(Void... params) {
String url = "http://sample.com/sample_data.json";
HttpGet getRequest = new HttpGet(url);
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/example.json");
System.out.println(file);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse getResponse = httpClient.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
System.out.println(this.response);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
StringBuilder builder = new StringBuilder();
for (Shop shop : this.response.shops) {
builder.append(String.format("<br>ID: <b>%s</b><br>Shop: <b>%s</b><br>Description: <b>%s</b><br><br>", shop.getId(), shop.getName(), shop.getDescription()));
}
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
}
private class CancelListener implements OnCancelListener {
AsyncTask<?, ?, ?> cancellableTask;
public CancelListener(AsyncTask<?, ?, ?> task) {
cancellableTask = task;
}
#Override
public void onCancel(DialogInterface dialog) {
cancellableTask.cancel(true);
}
}
}

Don't save the JSON file as it is. JSON is meant for transferring values from one place to another.
Instead, depending on the data, you can use Shared Preference or SQLite database to store it.
Check this out:
http://developer.android.com/guide/topics/data/data-storage.html
Then you can easily retrieve it and make modifications to the data.

Related

I can't retrieve data from server to android studio although data is shown in a browser

I have recently made an application in android studio 2.3 to show data from a server the link that I use is working properly in a browser and data is shown successfully in json format. But in my application I can't retrieve these data, I add avolley lib in my app gradle file like this :
compile 'com.mcxiaoke.volley:library:1.0.18'
The code I use in MainActivity is :
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String url = "http://abdulwahid.esy.es/show.php";
TextView txtshow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtshow = (TextView) findViewById(R.id.txtshow);
rq = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarr = response.getJSONArray("allstudents");
for (int i = 0; i < jarr.length(); i++) {
JSONObject res = jarr.getJSONObject(i);
String id = res.getString("id");
String name = res.getString("name");
String info = res.getString("info");
txtshow.append("\n" + id + " - " + name + "\n" + info + "\n" + "------------------" + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
rq.add(jor);
}
The link of php file that I use is executed successfully in a web browser.
How to show data in my application or is there another code or library to use for retrieving data form online ?
you can use StringRequest instead of jsonObject with the new library of volley
compile 'com.android.volley:volley:1.0.0'
Use this code to retrieve data, in string line your data will be appended as a complete string as shown in browser
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abdulwahid.esy.es/show.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
The problem is that the Content-Type header is not set in the response of your server. For Volley to be able to parse it, you will need that header set to application/json.
Add the following line in your show.php:
header('Content-Type: application/json');
Edit
After the above change, the response seems strange...
I can see strange characters in the response, that might be causing parsing issues on the client side.

How can I get filleUploaded URL as string from async task in android

I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.

Resuse of Async task code in my various file

I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}

Properly Using AsyncTask get()

I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

Read data from database located at server in android

I have one database file whose name is menu.db and this file is located at server now i want to read data from this database.
i also have registration page on the application i am working on, as user press submit button then all the user information should be store on that database at server.
if anyone solved this problem then please help me.
if any one knows then please help me.
I have the following code. It authenticates the user password. you should call this method inside doBackground() of AsyncTask extended Class.
public boolean authenticate(String strUsername, String strPassword)
{
boolean bReturn = false;
InputStream pInputStream = null;
ArrayList<NameValuePair> pNameValuePairs = new ArrayList<NameValuePair>();
pNameValuePairs.add(new BasicNameValuePair("userid", strUsername));
pNameValuePairs.add(new BasicNameValuePair("password", strPassword));
try
{
HttpClient pHttpClient = new DefaultHttpClient();
String strURL = p_strServerIP + "Login.php";
HttpPost pHttpPost = new HttpPost(strURL);
pHttpPost.setEntity(new UrlEncodedFormEntity(pNameValuePairs));
HttpResponse pHttpResponse = pHttpClient.execute(pHttpPost);
HttpEntity pHttpEntity = pHttpResponse.getEntity();
pInputStream = pHttpEntity.getContent();
BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(pInputStream,"iso-8859-1"),8);
StringBuilder pStringBuilder = new StringBuilder();
String strLine = pBufferedReader.readLine();
pInputStream.close();
if(strLine != null)
{
if((strLine).equals("permit"))
{
bReturn = true;
}
}
}
catch (Exception e)
{
Log.e("log_tag", "Caught Exception # authenticate(String strUsername, String strPassword):" + e.toString());
}
return bReturn;
}
The class you extend from AsyncTask should be something like
class ConnectionTask extends AsyncTask<String, Void, Boolean>
{
private SharedPreferences mSettings;
private Context mContext;
ConnectionTask(SharedPreferences settings, Context context)
{
mSettings = settings;
mContext = context;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Boolean result)
{
Toast.makeText(mContext, "Authentication over.", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... params)
{
pVerifier.authenticate(params[0], params[1]);
return true;
}
}

Categories

Resources