the code i am using is working very fine for me but the problem is i am not able to fetch that data in main activity
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
String username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
this is the code new AsyncTaskParseJson().execute(); to make this thing work
but i need to run
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}`
I want to get the data like firstname , lastname , username as variable in main activity .
Is it possible ??
this is my other class IncomingCall.java when i want to get the variables
public class IncomingCall extends BroadcastReceiver {
private String firstname;
private String lastname;
private String username;
public void onReceive (Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, " Calling "+username, Toast.LENGTH_LONG).show();
try {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
notifyuser=true;
}
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(context, "Error detected 1 "+e, Toast.LENGTH_LONG).show();
}
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
// for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(0);
// Storing each json item in variable
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
// }
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
protected void onPostExecute(String strFromDoInBg) {
Log.e("TAG1", "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
}
this is my code
The method onPostExecute runs on the main thread, You need to use the data once the doInBackground finishes and control return to the main thread.
Better you use these data in the method
protected void onPostExecute(String strFromDoInBg) {
// use the firstname , lastname or username after this method call.
}
Put your code in your Main Activity class, and then use class variables to store what you want, e.g.:
public class MainActivity extends Activity {
private String[] firstname;
private String[] lastname;
private String[] username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
firstname = new String[dataJsonArr.length()];
lastname = new String[dataJsonArr.length()];
username = new String[dataJsonArr.length()];
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
firstname[i] = c.getString("firstname");
lastname[i] = c.getString("lastname");
username[i] = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Something like this (it's without error checking, give it a try)
EDIT: be sure to have declared the internet permission in the android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Related
I am back from taking a few years break in programming. Today I am trying to access my webserver from android and I have some code I recycled from back in the day. The code used to work, but, lo and behold, today it has an error. Can someone help me figure this out?
Here is my main class:
public class login extends AppCompatActivity {
Button join;
TextView clientid;
EditText username, password;
_upload upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
upload = new _upload();
String android_id = Secure.getString(login.this.getContentResolver(),
Secure.ANDROID_ID);
join = findViewById(R.id.join);
clientid = findViewById(R.id.clientid);
clientid.setText(android_id);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}});
}
public void login(){
String id = username.getText().toString();
if (id.isEmpty()) { username.setError("required");username.requestFocus();return; }
String pw = password.getText().toString();
String cid = clientid.getText().toString();
String[] params = new String[3];
params[1]="username::" + id;
params[2]="password::" + pw;
params[3]="cid::" + cid;
new upload.send(login.this, "dump.php", params);
Toast.makeText(this, id + " " +pw+ " "+cid, Toast.LENGTH_LONG).show();
}
}
my error is in the line new upload.send(login.this, "dump.php", params);
error: cannot find symbol
new _upload.send(login.this, "dump.php", params);
^
symbol: class send
location: class _upload
this is my second class, the one that used to work:
public class _upload extends AppCompatActivity {
HttpURLConnection conn = null;
String Return;
String homeurl = "removed";
String roomurl = "";
String param;
Context ctx;
String er;
public void location(Context context, String url, String params){
ctx = context;
roomurl = url;
try {
param = "lola=" + URLEncoder.encode(params, "UTF-8");
new sendStatusChange_Server().execute("");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void send(Context context, String url, String params[]){
ctx = context;
roomurl = url;
int total = params.length;
int i = 0;
while(i<=total-1) {
if (i==0) {
try {
String[] keyval = params[0].split("::");
param = keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
else{
try {
String[] keyval = params[i].split("::");
param = param + "&" + keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
}
new sendStatusChange_Server().execute("");
}
public class sendStatusChange_Server extends AsyncTask<String, String, Void> {
protected Void doInBackground(String... params) {
try {
updateserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(er!=null){Toast.makeText(ctx, er, Toast.LENGTH_LONG).show();}
else{Toast.makeText(ctx, Return, Toast.LENGTH_LONG).show();}
}
}
private void updateserver() throws IOException {
URL url = new URL(homeurl + roomurl);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("SENT:", param + " to " + url.toString());
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
inStream.close();
Return = response;
} catch (MalformedURLException ex) {
} catch (IOException ex) {
er = ex.toString();
}
return;
}
}
the code still runs fine on the old program but I made a new package and want to get that rolling... why would this happen? Thank you for taking the time!
You have a syntax error. Use
upload.send(...)
instead of
new upload.send(...)
since upload is already an instance of your class.
You should probably also make it so _upload doesn't extend AppCompatActivity (just remove the extends AppCompatActivity from public class _upload extends AppCompatActivity).
I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}
public class MainActivity extends AppWidgetProvider
{
TextView tv;
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context,appWidgetManager,appWidgetIds);
for(int i=0; i<appWidgetIds.length; i++){
int currentWidgetId = appWidgetIds[i];
views = new RemoteViews(context.getPackageName(),R.layout.activity_main);
appWidgetManager.updateAppWidget(currentWidgetId,views);
new PostTask().execute("url");
}
}
private class PostTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
// Dummy code
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(1, TimeUnit.MINUTES); // connect timeout
client.setReadTimeout(1, TimeUnit.MINUTES); // socket timeout
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "data=something");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "7a4d5df8-5aed-19bf-e1fb-c85f821c1d10")
.addHeader("content-type", "application/x-www-form-urlencoded")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e1) {
e1.printStackTrace();
return e1.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(result);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response_data");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("CDRId").toString());
String name = jsonObject.optString("Status").toString();
data += "Agent : " + (i + 1) + "\nCDRId : " + id + " \n Status : " + name + " \n ";
}
views.setTextViewText(R.id.tv,data);
} catch (Exception e) {
views.setTextViewText(R.id.tv,e.toString());
}
}
}
}
I am trying to get a part of JSON(that I have parsed previously) in a widget. I am using AsyncTask to separate it from main thread and I am using OkHttpClient library to get JSON. I have class PostTask that gets me the parsed JSON. But can please anyone tell me how can I display it in the widget. This is the code.
Create a custom event, something like this:
public class MyEvent {
private String text;
public MyEvent(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text= text;
}
}
Now at the place where you're posting the Event, simply create this custom Event with the json you want to send to your widget. (put this code in onPostExecute).
EventBus.getDefault().post(new MyEvent(result);
Now simply wherever your textView is, in Activity or Fragment, register the eventBus in onCreate:
EventBus.getDefault().register(this);
And create a method that listens for the event like this:
#Subscribe
public void onMyEvent(MyEvent myEvent){
String text = myEvent.getText();
//Now you can parse this text, if it's JSON, or you can simply set it
//to your textView or whatever
}
I want take the information of a list view made with a hasmap and for this i have made this code:
public class MainActivity extends Activity {
ListView rdv;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> rdvous = new ArrayList<>();
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
URL = "http://172.16.32.101/?mot=listerrdv&id=5";
rdv = (ListView)findViewById(R.id.listRDV);
new HttpAsyncTask().execute(URL);
rdv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),map.get("titre"),Toast.LENGTH_LONG).show();
}
});
}
.
.
.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
String str = "";
for(int i = 0 ; i<json.length() ; i++) {
map = new HashMap<String, String>();
str ="";
str += "RDV " + (i+1) + "\n";
str += "jour: " + json.getJSONObject(i).getString("jour") + "\n";
str += "heure: " + json.getJSONObject(i).getString("heure") + "\n";
str += "perso: " + json.getJSONObject(i).getString("perso") + "\n";
str += "acte: " + json.getJSONObject(i).getString("acte") + "\n";
map.put("titre",str);
str = "";
str += json.getJSONObject(i).getString("idrdv");
map.put("description",str);
rdvous.add(map);
}
SimpleAdapter adapt = new SimpleAdapter (getBaseContext(), rdvous, R.layout.list_rdv,
new String[] {"titre", "description"}, new int[] {R.id.titre, R.id.description});
rdv.setAdapter(adapt);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I receive data and listview is Ok but when I click on an item, i only receive the last item...
Can you help me?
Rami found this solution:
Toast.makeText(getBaseContext(), rdvous.get(position).get("titre"),Toast.LENGTH_LONG).show();
And it's work
Thank Rami ;-)
Have the following AsyncTask code:
private class checkChangesTask extends AsyncTask<String, Void, String> {
protected ProgressDialog mProgressDialog2;
protected String _url = "", _idautor="", _idbook="";
#Override
protected void onPreExecute() {
super.onPreExecute();
this.mProgressDialog2 = new ProgressDialog(MainActivity.this);
this.mProgressDialog2.setMessage("Check changes ...");
this.mProgressDialog2.setIndeterminate(false);
this.mProgressDialog2.setCanceledOnTouchOutside(false);
this.mProgressDialog2.setCancelable(true);
this.mProgressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mProgressDialog2.setMax(100);
this.mProgressDialog2.setProgress(0);
this.mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[0];
_idbook = params[1];
_url = params[2];
try {
doc = Jsoup.connect(_url).userAgent("Mozilla").get();
Elements dd = doc.select("dd");
int size = dd.size();
int p = 1;
for (Element src : dd) {
this.mProgressDialog2.setProgress(p*100/size);
if (p <= size-1){
_html += src.outerHtml();
++p;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
String lastfile = readPageFile(_idautor + "_" + _idbook);
if(!lastfile.equals(result)){
savePageToFile(_idautor + "_" + _idbook, result);
}
}else{
Toast.makeText(MainActivity.this, "Error checkChangesTask", Toast.LENGTH_SHORT).show();
}
this.mProgressDialog2.dismiss();
}
the previous code I call in a loop:
public void checkChanges() {
String[][] db_books = db.selectAllBOOKS();
if (db_books.length>0){
for (int j = 0; j < db_books.length; j++){
new checkChangesTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, db_books[j][1], db_books[j][0], db_books[j][2]);
}
}
}
Everything works fine, but the dialog does not display the correct value. First, it is worth it to 0% and then abruptly switches to 100%.
AsyncTask called in sequence (...executeOnExecutor(AsyncTask.SERIAL_EXECUTOR...).
If you run a AsyncTask not in the loop, all the displays are just perfect!
android: targetSdkVersion = "14"
I ask your help.
You need to use onProgressUpdate() inside the AsyncTask. Something like this (at a guess)
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
this.mProgressDialog2.setProgress(progress[0] * 100/progress[1]);
}
And replace this line:
this.mProgressDialog2.setProgress(p*100/size);
With this:
publishProgress(new int[]{p,size})