Android TableView with MSSQL - android

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.

Related

SQL query with listview

I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.

Data won't be retrieved from mySQL by using JDBC in android studio

I am trying to retrieve data from mySQL in android studio, However i cannot return any value, but some error pops up at the logcat. Here are my codes:
My table:
For Connection Class:
I used AsyncTask on MainActivity:
private class viewDetail extends AsyncTask<String, String, String> {
String z = "";
boolean isSuccess = false;
String about;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Please check your internet connection";
} else {
String query = "select * from medicines where name ='amoxicillin'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
about = rs.getString("about");
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions" + ex;
}
return z;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getBaseContext(), about + z, Toast.LENGTH_LONG).show();
if (isSuccess) {
Toast.makeText(getBaseContext(), "Success!", Toast.LENGTH_LONG).show();
}
}
}
There's my code, quite messy. But the thing is I can't retrieve any data,
The error says "The url cannot be null"
Why are you doing getConnection twice in the Connection class? As you see, the second one has a null String as argument (ConnURL).
Remove that second attempt and it should do.
Also, please, don't add code to your questions as screenshots. Copy as text next time.

Async task does not let me override onPostExecute (method does not override method from it's superclass)

i'm creating an app that grabs list of playlists on YouTube. It used to be a list of videos, but i've changed the code and now it did not let me override that method.
My understanding is that i should change the "extends AsyncTask" with the new Playlist value instead of Video as it was before, but it still did not work.
it was:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Video>>> {
and now is:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Playlist>>> {
This is where is the error:
mPlaylist = new Playlist(mPlaylistId);
initAdapter(mPlaylist);
new GetPlaylistAsyncTask(mYouTubeDataApi, mTitle, mSearchQuery) {
#Override
public void onPostExecute(Pair<String, List<Playlist>> result) {
handleGetPlaylistResult(mPlaylist, result);
}
}.execute(mPlaylist.playlistId, mPlaylist.getNextPageToken());
And this is the AsyncTask:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Playlist>>> {
private static final String TAG = "GetPlaylistAsyncTask";
private static final Long YOUTUBE_PLAYLIST_MAX_RESULTS = 50L;
private static final String YOUTUBE_VIDEOS_PART = "snippet,contentDetails,statistics"; // video resource properties that the response will include.
private static final String YOUTUBE_VIDEOS_FIELDS = "items(id,snippet(title,description,thumbnails/high),contentDetails/duration,statistics)"; // selector specifying which fields to include in a partial response.
private YouTube mYouTubeDataApi;
private String mTitle;
private String mSearchQuery;
public GetPlaylistAsyncTask(YouTube api, String title, String searchQuery) {
mYouTubeDataApi = api;
mTitle = title;
mSearchQuery = searchQuery;
}
#Override
protected Pair<String, List<Playlist>> doInBackground(String... params) {
SearchListResponse searchResponse;
try {
YouTube.Search.List search = mYouTubeDataApi.search().list("id,snippet");
search.setKey(ApiKey.YOUTUBE_API_KEY);
search.setQ(mTitle + " " + mSearchQuery);
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(YOUTUBE_PLAYLIST_MAX_RESULTS);
searchResponse = search.execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (searchResponse == null) {
Log.e(TAG, "Failed to get playlist");
return null;
}
ArrayList videoIds = new ArrayList();
for (SearchResult item : searchResponse.getItems()) {
videoIds.add(item.getId().getVideoId());
}
VideoListResponse videoListResponse = null;
try {
videoListResponse = mYouTubeDataApi.videos()
.list(YOUTUBE_VIDEOS_PART)
.setFields(YOUTUBE_VIDEOS_FIELDS)
.setKey(ApiKey.YOUTUBE_API_KEY)
.setId(TextUtils.join(",", videoIds)).execute();
} catch (IOException e) {
e.printStackTrace();
}
return new Pair(searchResponse.getNextPageToken(), videoListResponse.getItems());
}
}
i don't get what is wrong on my code, i'll appreciate if you can point me on the right direction. Thanks in advance!
I've figured it out. The "onPostExecute" takes the object that doInBackground returns, as this post says:
stackoverflow post
Thanks to all for your answers, especially to #Enzokie
Just change public to protected since onPostExecute is not public by design.
#Override
protected void onPostExecute(Pair<String, List<Playlist>> result) {
handleGetPlaylistResult(mPlaylist, result);
}

Android Database in AsyncTask in Fragment

I have a DbHelper Class which extends SQLiteOpenHelper.
I do Some Download and update the Database inside an Asynctask.
Inside an activity i got no problem and code works fine,
but when i use the ASynctask class inside a fragment problems occurs.
usually wherever i use a context an Exception happened, Especially with dbHelper.ClearDB()
Error:
DB Read ERROR:java.lang.NullPointerException:
Attempt to invoke virtual method 'java.util.ArrayList x.database.DBHelper.getAllItems()' on a null object reference
Here's the code :
public class StaggeredFragment extends Fragment
{
private DBHelper dbHelper;
private SharedPreferences preferences;
private ArrayList<DisItem> savedData;
private final String LINK1 = "myLink";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbHelper = new DBHelper(getActivity().getApplicationContext());
preferences = getActivity().getSharedPreferences("pid", Context.MODE_PRIVATE);
new LoaderAsyncTask("ALL").execute();
}
class LoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
String brand;
LoaderAsyncTask(String brand) {
this.brand = brand;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.d(TAG,"RUnning");
String fetched;
InputStream is = null;
//Store Current Data before Sync
try {
savedData = dbHelper.getAllItems();
}catch (Exception e)
{
Log.d(TAG,"DB Read ERROR:"+e.toString());
return false;
}
try {
dbHelper.ClearDB();
}catch (Exception e)
{
Log.d(TAG,"DB Clear ERROR:"+e.toString());
return false;
}
// Open connection to server for html
try {
is = urlStream(LINK1);
} catch (Exception e) {
Log.e(TAG, "HTTP Error " + e.toString());
return false;
}
// Fetch HTML Data
try {
fetched = readIt(is);
// Log.d("fetched", fetched);
} catch (Exception e) {
Log.e(TAG, "Buffer Error " + e.toString());
return false;
}
// Parsing JSON
try {
if (!fetched.isEmpty())
InitialsJson(fetched);
}catch (JSONException e) {
Log.e(TAG, "JSON Error " + e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(!aBoolean)
RestoreData();
}
}
private void InitialsJson(String fetched) throws JSONException
{
JSONObject jsonObject = new JSONObject(fetched);
if (jsonObject.getInt("success") == 1) {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
DisItem disItem = new DisItem();
disItem.setPid(object.getString("pid"));
disItem.setLiked(preferences.getBoolean(String.valueOf(disItem.getPid()), false));
Log.d(TAG, disItem.toString());
dbHelper.insert(disItem);
}
}
}
This is Databace getallItems function
public ArrayList<DisItem> getAllItems()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DIS_TABLE_NAME + "", null);
ArrayList<DisItem> arrayList = new ArrayList<>();
cursor.moveToFirst();
while (! cursor.isAfterLast())
{
DisItem disItem = new DisItem(cursor);
arrayList.add(disItem);
cursor.moveToNext();
}
return arrayList;
}
I tried your code with same scenario in a small JUnit Test and it shows me that you have not initialized your ArrayList<DisItem> correctely in getAllItems() method may be thats why you are getting nullPointerException that is
Replace
ArrayList<DisItem> arrayList = new ArrayList<>();
With
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();'
I corrected this thing and run the test again with some dummy values and it showed me correct result like:
public class Test
{
private ArrayList<DisItem> savedData;
#org.junit.Test
public void test() throws Exception
{
savedData = getAllData();
for(int a = 0; a < savedData.size(); a++){
System.out.println("ArrayList Data A= " + savedData.get(a).getA() + " B = " + savedData.get(a).getB());
}
}
}
private ArrayList<DisItem> getAllData()
{
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();
DisItem disItem = new DisItem();
disItem.setA("AAAAAA");
disItem.setB("BBBB");
arrayList.add(disItem);
return arrayList;
}
private class DisItem
{
String a, b;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
}
Output:
ArrayList Data A= AAAAAA B = BBBB
you cant access more than one SharedPreferences or SQLiteOpenHelper in Parallel.

Issue about using Async with an Android Client

I am currently creating a project that needs to have a simple async task to take care of a thread running behind the scenes. The user needs to login. I am using another class called PVAndroid Client that supplies useful methods and has an XML serializer form packets for me. I am completely new to working with threads or doing anything with servers, so this may be completely wrong or somewhat right.
I get the data the user entered: the ip address and port, their username (I split this into first and last name), their region they selected. I encrypt their password, and attempt to connect to the tcp using ip address and port number. I am trying to work in the async task but am kind of confused on what I should do. Can anyone guide me in the right direction and help me out?
Thank you I really appreciate it.
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String USERNAME_SHARED_PREFS = "username";
private static final String PASSWORD_SHARED_PREFS = "password";
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptedNameLoginActivity, encryptPassLoginActivity;
private EditText userText, passText;
private String getIpAddressSharedPrefs, getPortNumberPrefs;
private String getUserNameValue;
private String getPasswordValue;
private String fName, lName;
private SharedPreferences settings;
private Editor myEditor;
private boolean getCheckedRemember;
private boolean resultCheck = false;
private int portNum;
private Button submitButton;
private String userMACVARIABLE = "";
private String regionSelected, gridSelected;
private Spinner regSpinner, gridSpinner;
PVDCAndroidClient client;
private int userNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
submitButton = (Button) findViewById(R.id.submitButton);
userText = (EditText) findViewById(R.id.nameTextBox);
passText = (EditText) findViewById(R.id.passwordTextBox);
regSpinner = (Spinner) findViewById(R.id.regionSpinner);
// grid selected as well? sometime?
regSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long rowId) {
regionSelected = regSpinner.getItemAtPosition(position)
.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
submitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
settings = PreferenceManager
.getDefaultSharedPreferences(AndroidClientCompnt.this);
getIpAddressSharedPrefs = settings.getString(
IP_ADDRESS_SHARED_PREFS, "");
portNum = Integer.parseInt(settings.getString(
PORT_SHARED_PREFS, ""));
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
if (userText.length() != 0 && passText.length() != 0) {
try {
try {
// encrypting the user's password.
encryptPassLoginActivity = Secure.encrypt(passText
.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// first connect attempt.
myTcpClient = new TcpClient();
myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect.", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
}
}
});
}
private class UploadTask extends AsyncTask<String, Integer, Void>
{
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
resultCheck = myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
if (resultCheck == true) {
while (myTcpClient.getUserNum() < 0) {
// num set? session? with proxy server?
}
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = userText.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,regionSelected, 128, 128, 20);
} else {
Toast.makeText(getApplicationContext(),
"Connection not successful", Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
First
#Override
protected Void doInBackground(String...params) {
new Thread (new Runnable() {
// ...
}
}
Never do this again. There is no need to create new Thread in doInBackground method which actually running on background Thread. So remove it.
The advice to you is tricky because you need to read about Threads, work with Connection etc. So the best advice to you is to read some tutorials, examples of basic applications and read references. So you can start here:
Android TCP Client and Server Communication Programming–Illustrated with Example
I cannot see, where you are yoursing your Task, but I see that you are doing something weired inside doInBackground()! There is absolutely NO reason, to create your own Thread inside it.
remove that, and you could just use your Task like this:
UploadTask task = new UploadTask();
task.execute("someString", "anotherString", "addAsManyStringsYouNeed");
The docs from AsyncTask are very helpfull, too.

Categories

Resources