Cannot resolve symbol 'execute' ... calling AsyncTask - java

I am trying to make a GET request on a URL, I created a class extending AsyncTask<Void, Void, Void> and I try to call new MyClass.execute() ... I have done this before and it worked, today it is not working. What am I doing wrong?
Here is my code:
public class SignUpActivity extends AppCompatActivity {
String TAG = SignUpActivity.class.getSimpleName();
String URL;
ArrayList<String> countries = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
new MyClass.execute();
}
private class MyClass extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, "GET");
//Handling response in jsonStr code
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//TODO
}
}

This is a syntax error. It should be
new MyClass().execute();
not as new MyClass.execute();

use this to get data use return to return value:
public class SignUpActivity extends AppCompatActivity {
String TAG = SignUpActivity.class.getSimpleName();
String URL;
ArrayList<String> countries = new ArrayList<>();
String jsonStr="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
String response = new MyClass.execute();
}
private class MyClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODP
}
#Override
protected String doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, "GET");
//Handling response in jsonStr code
return jsonStr;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//TODO
jsonStr = result;
}
}
}

public class JsonHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public JsonHandler() {
}
public String makeServiceCall(String url,int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (Exception e) {
}
return response;
}
}
Add above class to your main package and do it as doInBackground
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
JsonHandler json = new JsonHandler();
String jsonStr = json.makeServiceCall(params[0], JsonHandler.GET);
// parse your json data here
}

Related

Can't load my data from MySQL even though php code is working?

I am a newer android developer , and i try to make an app which depend on MySQL.
so i have MySQL database and I have A php that return its data in Json format at this link here.
so i make a simple app that take this data and show it in list view by AsyncTask & Service Handler .
Note 1: I try this app with another database [Not Free Domain/website] and it work But with my database didn't work [free hosting]
Note 2: I try to comment the "Try & Catch" code at doInBackground method at AsyncTask class & make a dummy data manually So the app works !!, so what???!!
Update: i used the emulator and i got some red massages that i do not understand what its mean so i take it as screen shot
My php code:
<?php
$dbname = 'zoubg_18363398_center';
$dbserver = 'sql104.kariya-host.com';
$dbusername = 'zoubg_18363398';
$dbpassword = '28721235';
$dbconnect = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$getpostssql = "SELECT * FROM users";
$posts = $dbconnect->query($getpostssql);
$postsarray = array();
while($row = mysqli_fetch_array($posts, MYSQL_ASSOC)){
$temp['id'] = $row['id'];
$temp['name'] = $row['name'];
$temp['password'] = $row['password'];
$temp['email'] = $row['email'];
$temp['adress'] = $row['adress'];
array_push($postsarray, $temp);
}
echo json_encode(array("posts"=>$postsarray), JSON_UNESCAPED_UNICODE);
</blink>
My java code
public class MoveActivity extends AppCompatActivity {
ListView LVMove;
MoveAdapter moveAdapter;
ArrayList<MoveInfo> MoveList = new ArrayList<>();
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move);
LVMove = (ListView) findViewById(R.id.lv_test);
// dummy data manually
/*
MoveInfo Move1 = new MoveInfo();
Move1.setId(1);
Move1.setSName("Ahmed");
Move1.setSPass("123456");
Move1.setSEmail("Ahmed#asdf.com");
Move1.setSAddress("CairoEgypt");
MoveList.add(Move1);
MoveInfo Move2 = new MoveInfo();
Move2.setId(2);
Move2.setSName("Ali");
Move2.setSPass("456789");
Move2.setSEmail("Ali#asdf.com");
Move2.setSAddress("AlexEgypt");
*/
new GetMoves().execute("http://centertest.kariya-host.com/testjjjsn.php");
}
class GetMoves extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MoveActivity.this);
pDialog.setMessage(" Please wait ... ");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... strings) {
String url = strings[0];
ServiceHandler serviceHandler = new ServiceHandler();
JSONObject jsonObject = serviceHandler.makeServiceCall(url, ServiceHandler.GET);
try {
JSONArray DATA = jsonObject.getJSONArray("posts");
for (int i = 0; i < DATA.length(); i++) {
JSONObject item = DATA.getJSONObject(i);
MoveInfo Move = new MoveInfo();
int id = item.getInt("id");
String name = item.getString("name");
String password = item.getString("password");
String email = item.getString("email");
String adress = item.getString("adress");
Move.setId(id);
Move.setSName(name);
Move.setSPass(password);
Move.setSEmail(email);
Move.setSAddress(adress);
MoveList.add(Move);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(pDialog.isShowing()){
pDialog.dismiss();
moveAdapter = new MoveAdapter(MoveList, getApplicationContext());
LVMove.setAdapter(moveAdapter);
}
}
}
}
ServiceHandler Code
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public JSONObject makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public JSONObject makeServiceCall(String url, int method,
List<NameValuePair> params) {
JSONObject jsonObject=null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
jsonObject=new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
MoveAdapter code
public class MoveAdapter extends BaseAdapter {
ArrayList<MoveInfo> MoveList;
Context context;
LayoutInflater inflater ;
public MoveAdapter (ArrayList<MoveInfo> MoveList, Context context){
this.MoveList = MoveList;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return MoveList.size();
}
#Override
public Object getItem(int i) {
return MoveList.get(i);
}
#Override
public long getItemId(int i) {
return MoveList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.item_list, null);
}
TextView TvIds = (TextView) view.findViewById(R.id.tv_Ids);
TextView TvNames = (TextView) view.findViewById(R.id.tv_Names);
TextView TvPasss = (TextView) view.findViewById(R.id.tv_Passs);
TextView TvEmails = (TextView) view.findViewById(R.id.tv_emails);
TextView TvAddresss = (TextView) view.findViewById(R.id.tv_addresss);
TvIds.setText(MoveList.get(i).getId()+"");
TvNames.setText(MoveList.get(i).getSName());
TvPasss.setText(MoveList.get(i).getSPass());
TvEmails.setText(MoveList.get(i).getSEmail());
TvAddresss.setText(MoveList.get(i).getSAddress());
return view;
}
}
update: every thing was right, problem was in hosting server when i change hosting server , every thing work probably Thanks for interresting

Java Interface Callback on Android

I am currently trying to make an android app that basically downloads strings from a url. But I want to make it object oriented. My mainActivity gets string from webService which downloads string when button is clicked. But I am not good at interfaces and callbacks. What should I do to make this code run?
public class MainActivity extends Activity implements WebServiceInterface{
private TextView textView;
private Button readWebPage;
private WebService service;
private WebServiceInterface webServiceInterface;
private String response;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
readWebPage = (Button) findViewById(R.id.readWebpage);
service = new WebService();
readWebPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
service.execute(new String[]{"http://google.com/"});
onSuccess(response);
}
});
}
#Override
public void onSuccess(String response) {
textView.setText(Html.fromHtml(response));
}
#Override
public void onFail(Exception ex) {
textView.setText(ex.getLocalizedMessage());
}
}
public class WebService extends AsyncTask<String, Void, String> {
private WebServiceInterface webServiceInterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webServiceInterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webServiceInterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public interface WebServiceInterface {
void onSuccess(String response);
void onFail(Exception ex);
}
you need to create one public method for set webServiceInterface in WebService class like
public setWebServiceInterface (WebServiceInterface listener)
{
this.webServiceInterface =listener;
}
in MainActivity activity call this method and pass argument this
service.setWebServiceInterface (this);
in WebService class in onPostExecute Method call
webServiceInterface.onSuccess(s);
Add WebService (WebServiceInterface webServiceInterface) in your AsyncTask as a constructor.
service = new WebService(new WebServiceInterface (){
void onSuccess(String response){
//do your stuff
}
void onFail(Exception ex){
//do your stuff
}
});
and in your asynctask
public class WebService extends AsyncTask<String, Void, String> {
public WebService (WebServiceInterface webServiceInterface){
this.webinterface= webServiceInterface;
}
private WebServiceInterface webinterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webinterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webinterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I have found the problem, it is because of runOnUiThread is missing.

Android, it failed to upload an image to server

I am trying to upload an image file using multipart method to the server.
Here are my codes.
package com.example.test_multipart;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
TestAsyncTask asyncTask = new TestAsyncTask();
#Override
public void onClick(android.view.View v) {
// TODO Auto-generated method stub
new TestAsyncTask().execute();
}
});
}
public class TestAsyncTask extends AsyncTask<HttpResponse, Integer, Long> {
private ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
long totalSize;
String url = "http://bridgecall.co.kr:5000/apis/settings/profile_update";
#Override
protected Long doInBackground(HttpResponse... arg0) {
// Register parameters
Map<String, Object> params = new HashMap<String, Object>();
params.put("phone", "01030195208");
params.put("name", "YUJIHYN");
Map<String, File> fileParams = new HashMap<String, File>();
File f = new File("/DCIM/Camera/test.jpg");
fileParams.put("file", f);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Accept-Charset", "UTF-8");
httpPost.setHeader("ENCTYPE", "multipart/form-data");
CustomMultipartEntity multipart = new CustomMultipartEntity(
new ProgressListener() {
#Override
public void transferred(long transferred) {
// TODO Auto-generated method stub
publishProgress((int) transferred);
}
});
// Params
for (String strKey : params.keySet()) {
StringBody body = new StringBody(params.get(strKey)
.toString());
multipart.addPart(strKey, body);
}
// attach a file
for (String keys : fileParams.keySet()) {
multipart.addPart(keys, new FileBody(fileParams.get(keys)));
}
totalSize = multipart.getContentLength();
mDialog.setMax((int) totalSize);
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpPost);
Log.v("checkcheckcheckcheck ", "checkcheckcheckcheck");
HttpEntity entity=response.getEntity();
InputStream is = entity.getContent();
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).append("\n");
}
is.close();
} catch (Exception e) {
return 0L;
}
return 0L;
}
#Override
protected void onCancelled() {
super.onCancelled();
mDialog.dismiss();
}
#Override
protected void onPostExecute(Long result) { // ui.
super.onPostExecute(result);
mDialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setCancelable(true);
mDialog.setOnCancelListener(cancelListener);
mDialog.setMessage("Uploading...");
mDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Progress update
mDialog.setProgress((int) progress[0]);
}
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}
};
}
}
It doesn't work after this line.
Log.v("checkcheckcheckcheck ", "checkcheckcheckcheck");
I get 400 error from the server.
It works fine if I upload an image on HTML. Can you see what is the problem?

Passing Value of Asynctask in Fragment

I have been working with passing the result created by the onPostExecute of AsyncTask in Fragment.
I know how to do it in Activity, like ((MyActivity)context).someMethod();
But how can I do this in Fragment?
I do ((MyFragment)contextOfAsyncTask).methodInFragment() but it gives me an error "Cannot cast from Context to MyFragment".
Here is my code in AsyncTask
class AsyncMethod extends AsyncTask{
ArrayList<MyObject> myVar= new ArrayList<MyObject>();
String result;
ListView lv;
Context contextOfAsyncTask;
public AsyncMethod(Context xc, ListView xl){
contextOfAsyncTask= xc;
lv = xl;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void...param) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(http://www.myurl.com/something.php);
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
return null; //EVERYTHING IS WORKING FINE HERE, AND I CAN GET THE VALUE
}
#Override
protected void onPostExecute(Void res) {
//it does not work here
((MyFragment)contextOfAsyncTask).methodInFragment(result);
}
It is look like you want to call method from AsyncTask
class YourTask extends AsyncTask<Void, Void, Void> {
private SomeFragment fragment;
YourTask(SomeFragment fragment) {
this.fragment = fragment;
}
#Override
protected Void doInBackground(Void... params)
{
//do whatever you want to do
}
#Override
protected void onPostExecute(Void res)
{
fragment.yourmethod();
}
}
i hope it help..

CallBack gives a NullPointException

I'm trying to make a simple webreader work in an AsyncTast,
main thread
public class main extends Activity implements CallBackListener{
...
WebReader wr = new WebReader();
wr.execute("http://www.google.com");
...
#Override
public void callback(String res)
{
Log.e("eee",res);
}
...
}
...
interface CallBackListener
{
void callback(String res);
}
and webreader
class WebReader extends AsyncTask<String, Void, String>{
CallBackListener mListener;
public void setListener(CallBackListener listener){
mListener = listener;
}
#Override
protected String doInBackground(String... urls) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.e("s3","ss"+result);
mListener.callback(result); // null point here
}
}
yet it crashed with a nullpoint at mListener.callback ... any ideas what might be wrong?
Thanks!
You are not setting a listener. You should have something like this:
WebReader wr = new WebReader();
wr.setListener( new YourCallbackListener() );
wr.execute("http://www.google.com");

Categories