Null pointer exception running connected test in Android studio - android

I am trying to execute connected test for P4, however I am reciing an "Null pointer exception error" for P4
Error message:
:00:02 PM null
java.lang.NullPointerException
at com.android.ddmlib.Client.read(Client.java:692)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:304)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:256)
It is a standard test, verifying non-empty string in the Async task
Test function:
public void runCloudModuleTest() {
String joke = null;
JokesAsyncTask jokesAsyncTask = new JokesAsyncTask(getContext(), null);
jokesAsyncTask.execute();
try {
joke = jokesAsyncTask.get();
Log.d("CloudModuleTest", "Retrieved a non-empty string successfully: " + joke);
} catch (Exception e) {
e.printStackTrace();
}
assertNotNull(joke);
}
Can someone help me understand what the issue is?
AsyncTask: The Async task pulls data from google cloud engine
public class JokesAsyncTask extends AsyncTask, Void, String> {
private static JokeApi myApiService = null;
private Context mContext;
private String mResult;
private ProgressBar mProgressBar;
public JokesAsyncTask(Context context, ProgressBar progressBar) {
this.mContext = context;
this.mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (mProgressBar != null) {
mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(Pair<Context, String>... pairs) {
if (myApiService == null) {
JokeApi.Builder builder = new JokeApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https://testandroiddevelopment.appspot.com/_ah/api/");
myApiService = builder.build();
}
try {
return myApiService.sendJoke(new JokeBean()).execute().getJoke();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
mResult = result;
startJokeDisplayActivity();
}
private void startJokeDisplayActivity() {
Intent intent = new Intent(mContext, JokeViewActivity.class);
intent.putExtra(JokeViewActivity.JOKE_KEY, mResult);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
I have referenced the variable and it is not an issue due due to the below post, however I did investigate and finally cleaned up and rebuild the project that helped resolved the issue

I have referenced the variable and it is not an issue due due to the post #AxelH, however I did investigate and finally cleaned up and rebuild the project that helped resolved the issue

Related

ConditionVariable not working in AsyncTask

I need to wait for listener to check if image was sent correctly and then finish AsyncTask. But last log in logcat is "blocking...", so onComplete never triggers.
When I set initialization of condition varible to true, it's working but it doesn't wait on block(). I've seen many examples on ConditionVariable and I can't figure it out where my mistake is, it should be working.
private static class SendImageTask extends AsyncTask<SendImagePojo, Void, String> {
private String KOFAX_TAG = "kofax";
#Override
protected String doInBackground(SendImagePojo... params) {
Log.d(KOFAX_TAG, "doInBackground");
final ConditionVariable condition = new ConditionVariable(false);
params[0].kfx.sendImageService(params[0].doc, params[0].s, params[0].img, params[0].imageIndex, true, new ICompletionListener<Void>() {
#Override
public void onComplete(Void aVoid, Exception e) {
Log.d(KOFAX_TAG, "onComplete");
if (e != null) {
Log.e(KOFAX_TAG, e.getLocalizedMessage());
} else {
Log.d(KOFAX_TAG, "Image sent...");
}
condition.open();
}
});
Log.d(KOFAX_TAG, "blocking...");
condition.block();
Log.d(KOFAX_TAG, "continuing...");
return null;
}
}

Android TableView with MSSQL

I am busy with trying to get an array which i get from MSSQL to display in a table view form in my application. I have tried to google it but i cant seem to find an example of this. I have tried it but i am running into one small error.
I get the following error Cannot resolve constructor:Simpletabledata adapter[package.mainactivity, package.itemarray]
Here is my mainactivy.java class:
public class MainActivity extends AppCompatActivity {
static String[] spaceProbeHeaders={"Name"};
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
final TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
private boolean success = false; // boolean
Connection conn; // Connection Class Initialization
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableView.setHeaderBackgroundColor(Color.parseColor("#777777"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
tableView.setColumnCount(4);
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String>
{
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(MainActivity.this, "Synchronising",
"Tableview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try
{
ConnectionClass conStr=new ConnectionClass();
conn =conStr.connectionclass();
//Connection Object
if (conn == null)
{
success = false;
}
else {
// Change below query according to your own database.
String query = "SELECT customer_first_name FROM cc_customer";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next())
{
try {
itemArrayList.add(new ClassListItems(rs.getString("customer_first_name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false)
{
}
else {
try {
//myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
tableView.setDataAdapter(new SimpleTableDataAdapter(MainActivity.this,itemArrayList ));
} catch (Exception ex)
{
}
}
}
}
and here is my classlist.java file:
public class ClassListItems
{
public String name; //Name
public ClassListItems(String name)
{
this.name = name;
}
public String getName() {
return name;
}
Update
N.B: OP is using SortableTableView Library.
You need to import the following to solve Cannot resolve constructor:SimpleTableDataAdapter-
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
Original
Do you have SimpleTableDataAdapter class in your project? It seems it can't find the class so it is not in the same package. If it is in different package, you need to import it.
And on a different note, your .java file names should match the class name
And on another different note, have you tested that itemArrayList is actually populating? For Android-MSSQL, here is a tutorial pointer -
https://parallelcodes.com/connect-android-to-ms-sql-database-2/
There are many tutorials if you google it.

How to test AsyncTask class using Mockito

I have AsyncTask class as shown below in the code, and I am trying to test it.
I coded the test cases of the AsyncTask as shown below in the testing section, but as shown in the testing code, I just tested whether or not the AsyncTask
methods was called or not, and I did not tested the code in doInBackground() for example, because I do not know how to test it
Please let me know how to test AsyncTask class any guideline or hints are highly appreciated
code
public class AsyncTaskImageLoader extends AsyncTask<String, Void, RequestCreator> {
RequestCreator requCreator = null;
String picUrl = null;
private ImageView mImageView = null;
private UserAdapter.MyViewHolder mHolder = null;
ProgressBar mProgressBar = null;
Validation mValidation = null;
private Context mCtx = null;
public AsyncTaskImageLoader(Context ctx, UserAdapter.MyViewHolder holder) {
mHolder = holder;
mCtx = ctx;
mValidation = new Validation(ctx);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mHolder.progressBar.setVisibility(View.VISIBLE);
}
#Override
protected RequestCreator doInBackground(String... params) {
picUrl = params[0];
if (mValidation.isValidUrl(picUrl)) {
while (!isCancelled() && requCreator == null) {
try {
requCreator = mValidation.requestCreatorFromUrl(picUrl);
} catch (Exception e) {
}
//the value of the delay could be changed preferably
SystemClock.sleep(100);
}
}
return requCreator;
}
#Override
protected void onPostExecute(RequestCreator requestCreator) {
super.onPostExecute(requestCreator);
mHolder.progressBar.setVisibility(View.GONE);
//requestCreator.into(mHolder.imageViewAvatarOfOwner);
mValidation.setImageOnImageView(requestCreator, mHolder.imageViewAvatarOfOwner);
}
testing:
public class AsyncTaskImageLoaderTest {
#Mock
ProgressBar mockProgressBar = null;
#Mock
AsyncTaskImageLoader mockAsyncTaskImageLoader = null;
#Mock
Context mCtx = null;
#Before
public void setUp() {
mCtx = mock(Context.class);
mockProgressBar = mock(ProgressBar.class);
mockAsyncTaskImageLoader = mock(AsyncTaskImageLoader.class);
}
#Test
public void whenProgreeBarISSetToVisibleInOnPreExecute() throws Exception {
mockProgressBar.setVisibility(View.VISIBLE);
verify(mockProgressBar).setVisibility(View.VISIBLE);
}
#Test
public void whenOnDoInBackgroundIsCalled() throws Exception {
String str = new String();
mockAsyncTaskImageLoader.execute(str);
verify(mockAsyncTaskImageLoader).execute(str);
}
#Test
public void whenOnPostExecuteIsCalled() throws Exception {
RequestCreator mockRequestCreator = mock(RequestCreator.class);
mockAsyncTaskImageLoader.onPostExecute(mockRequestCreator);
}
}

Incompatible types .Required java.lang.Integer found java.lang.String

class EndpointsAsyncTask extends AsyncTask<Pair<Context, Integer>, Void, Integer> {
private static MyApi myApiService = null;
private Context context;
#Override
protected Integer doInBackground(Pair<Context, Integer>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}});
myApiService = builder.build();}
context = params[0].first;
int name = params[0].second;
try {
return myApiService.addition(name).execute().getNo1();
// return myApiService.addition(name).execute().getNo1();
} catch (IOException e){
return e.getMessage();
}
}
#Override
protected void onPostExecute(Integer result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
I want to send a no to google app engine from android endpoint.and want a number to be displayed on the google app engine page .But in return e.getMessage(); I found error incompatible types
protected void onPostExecute(Integer result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
(If "result" is not a resource ID)
Toast.makeText() takes String as 2nd parameter.
Try
Toast.makeText(context, "" + result, Toast.LENGTH_LONG).show();

Android - How to get calling Activity?

An Activity (SignInActivity) is calling a method in FunkcjeAPI which execute an AsyncTask.
My AsyncTask should show a ProgressDialog using an calling Activity. I don't know how to give it an correct Activity to the constructor. I tried a lot of thing, read a lot of tutorials and questions on SO, but I can't find solution. FunkcjeAPI isn't an Activity so I can't write new Logowanie(this).execute(argumenty);
AsyncTask calling code :
public class FunkcjeAPI {
static String dozwrotu = null;
public static String zalogujSie(final String nick, final String haslo)
{
String[] argumenty = {nick, haslo};
new Logowanie(/* WHAT HERE ? */).execute(argumenty); // HELP ME IN THAT LINE !!!!!!!!!!!!!
return dozwrotu;
}
My AsyncTask class code (it is in FunkcjeAPI class):
private class Logowanie extends AsyncTask<String, Void, String>
{
Activity wywolujaceActivity;
public Logowanie(Activity wywolujaceActivity) {
this.wywolujaceActivity = wywolujaceActivity;
}
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
wywolujaceActivity.showDialog(SignInActivit.PLEASE_WAIT_DIALOG);
}
#Override
protected String doInBackground(final String... argi) {
final JSONParser jParser = new JSONParser();
new Thread(new Runnable() {
public void run() {
final String json = jParser.getJSONFromUrl("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(json);
Log.wtf("Link", "http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
Log.wtf("Link", json);
String error = jObject.getString("error");
if(error == "You reached daily query limit !") { nadajWartosc("You reached daily query limit !"); }
if(error == "0") {nadajWartosc(jObject.getString("token"));}
if(error == "1") {nadajWartosc("1");}
if(error == "Invalid username") {nadajWartosc("Invalid username");}
if(error == "Invalid password") {nadajWartosc("Invalid password");}
if(error == "This user is already logged in !") {nadajWartosc("This user is already logged in !");}
} catch (JSONException e1) {
e1.printStackTrace();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
});
}}).start();
return dozwrotu;
}
#Override
protected void onPostExecute(String result) {
wywolujaceActivity.removeDialog(SignInActivit.PLEASE_WAIT_DIALOG);
}
}
Add one more parameter to zalogujSie() method that takes an Activity, and then use this parameter to start the AsyncTask:
public static String zalogujSie(Activity activity, final String nick, final String haslo)
{
// .....
new Logowanie(activity).execute(argumenty);
return dozwrotu;
}
Then you would call this method from the activity like this:
FunkcjeAPI.zalogujSie(this, "Nick", "Haslo");

Categories

Resources