Custom alert dialog not displaying JSON data from Asynctask's Post Execute - java

I have a weird problem with showing my custom alert dialog from inside my async task's post execute method. When the program is run, the progress dialog from my pre-execute is first of all dismissed in the post execute before I then display my custom alert dialog which displays parsed JSON data. But the custom alert dialog does not show up at all, after dismissing the progress dialog.
Please, can anyone help with possible reasons why that's happening? Here is the code from my post exec method.
#Override
protected void onPostExecute(String result) {
loginDialog.dismiss();
jsonstring = result;
try {
jsonObject = new JSONObject(jsonstring);
jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
fname = JO.getString("firstname");
lname = JO.getString("lastname");
possessionqty = JO.getString("possessionQty");
email = JO.getString("email");
status = JO.getString("status");
mBuilder = new AlertDialog.Builder(activity);
mView = getLayoutInflater().inflate(R.layout.studentinfo_alertdialog, null);
studentIDheader = (TextView) mView.findViewById(R.id.textView3);
studentfullname = (EditText) mView.findViewById(R.id.editText);
studentpossessionqty = (EditText) mView.findViewById(R.id.editText2);
studentemail = (EditText) mView.findViewById(R.id.editText3);
studentstatus = (EditText) mView.findViewById(R.id.editText4);
studentIDheader.setText(validatedID);
studentfullname.setText("Full Name: " + fname + " " + lname);
studentpossessionqty.setText("Possession Qty: " + possessionqty);
studentemail.setText("Email: " + email);
studentstatus.setText("Status: " + status);
mBuilder.setCancelable(false);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

How to loop ArrayList and send each value to Download Manager?

I am trying to send ArrayList(VideoUrlArrayList) values inside a for loop to Android Download Manager but i keep getting following error:
error: incompatible types: String cannot be converted to Uri
and pointing to this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));
if i remove the part of code that sends urls to Download Manager the toast displays the arrayList(VideoUrlArrayList) values correctly !
Could you guys help me fix this problem and successfully send values of my ArrayList to Download Manager?(Furthermore, I want to use the original file names from urls stored in VideoUrlArrayList).Thanks
MainAcitivty.java:
public class MainActivity extends AppCompatActivity {
private DownloadManager downloadManager;
private long refid;
private String fileName;
ArrayList<Long> list = new ArrayList<>();
ArrayList<String> VideoUrlArrayList =new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
TextView btnMultiple = (TextView) findViewById(R.id.multiple);
if(!isStoragePermissionGranted())
{
}
btnMultiple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.clear();
EditText editText1 = (EditText) findViewById(R.id.editText);
String linesArray[] = editText1.getText().toString().split("\n");
for (int i = 0; i < linesArray.length; i++) {
String currLine = linesArray[i];
VideoUrlArrayList.add(currLine);
}
for (int i = 0; i < VideoUrlArrayList.size(); i++) {
//Toast.makeText(getApplicationContext(), "Array Text: " + VideoUrlArrayList.get(i), Toast.LENGTH_LONG).show();
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Demo Downloading " + fileName);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading " + fileName);
//Set whether this download should be displayed in the system's Downloads UI. True by default.
request.setVisibleInDownloadsUi(true);
//Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
refid = downloadManager.enqueue(request);
Log.e("OUTNM", "" + refid);
list.add(refid);
}
}
});
//the rest of code after this
}
Make this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
to:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(VideoUrlArrayList.get(i)));
DoesnloadManager.Request() accepts Uri not String. So you need to parse it to Uri.

Android ListViewe Filtration for loading large amount of data from server

i am loading data from server to hashmap array and showing the data into listView.
As the data is big with images, i want to apply filter or pagination on listview to load only 10-15 item and when i click on load more or scroll down then next data appear in bottom of listView like facebook does.
I am using Glide API for loading images and using custome Adapter for setting data into listView.
final String propertyID = contactList.get(position).get("property_id").toString();
final String propertyTitle = contactList.get(position).get("property_title").toString();
final String price = contactList.get(position).get("price").toString();
String country = contactList.get(position).get("country").toString();
String city = contactList.get(position).get("city").toString();
String location = contactList.get(position).get("location").toString();
final String landArea = contactList.get(position).get("landArea").toString();
final String contact = contactList.get(position).get("phone").toString();
String propertyType = contactList.get(position).get("property_type").toString();
String propertystatus = contactList.get(position).get("status").toString();
String description = contactList.get(position).get("property_description").toString();
String rooms = contactList.get(position).get("rooms").toString();
String bathrooms = contactList.get(position).get("bathrooms").toString();
String floors = contactList.get(position).get("floors").toString();
String status_property = contactList.get(position).get("status_property").toString();
String dealer_email = contactList.get(position).get("dealer_email").toString();
tv_property_id.setText(propertyID);
tv_propertyTitle.setText(propertyTitle);
tv_price.setText(price);
tv_country.setText(country);
tv_propertyCity.setText(city);
tv_propertyPhone.setText(contact);
tv_propertyPropertyLandArea.setText(landArea);
tv_protperty_type.setText(propertyType);
tv_protperty_status.setText(propertystatus);
tv_protperty_description.setText(description);
tv_propertyLocation.setText(location);
tv_propertyEmail.setText(dealer_email);
tv_property_rooms.setText(rooms);
tv_property_bathrooms.setText(bathrooms);
tv_property_floors.setText(floors);
tv_property_status_prpoperty.setText(status_property);
//imageLoader.DisplayImage(contactList.get(position).get("imageurl"), image);
Glide.with(activity)
.load(contactList.get(position).get("imageurl"))
.placeholder(R.drawable.default_image)
//.error(R.drawable.)
.override(200, 200)
.centerCrop()
.into(image);
and Adapter code is
HashMap contact = new HashMap<>();
contact.put("property_id", property_id);
contact.put("imageurl", imageURL);
contact.put("property_title", property_title);
contact.put("price", price);
contact.put("landArea", landArea);
contact.put("country", country);
contact.put("city", city);
contact.put("phone", phone);
contact.put("property_type", propertyType);
contact.put("status", propertystatus);
contact.put("property_description", description);
contact.put("location", propertyLocation);
contact.put("dealer_email", dealer_email);
contact.put("rooms", rooms);
contact.put("bathrooms", bathrooms);
contact.put("floors", floors);
contact.put("status_property", status_property);
contactList.add(contact);
Log.e("TAG", "Image URL: " + imageURL);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Please Check your Internet Connection!",
Toast.LENGTH_LONG).show();
}
});
}
adapter=new DataAdapter(ShowProperties.this, contactList);
list.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
How does i apply filtration that it loading only 10, after scrolling down it load more ten and so on.
There are solutions ready for that case. I suggest you use one of working examples.
Here is one:
Endless Scrolling with AdapterViews and RecyclerView

Java/Android App unexpectedly closing / POSTing to server

I have no errors or warnings in Eclipse and I'm completely new to Android Programming so I don't even know where to start with this.
My app is just a simple form that I need to post to a php script online.
Here's the bulk of my main Activity minus the imports.. I don't have it set up to do anything with return values or any of that, and TBH i don't even know what would happen if it did work other than the data would be in my DB.. but the PHP script is not even being called by my app at all.
Based on things I found in Google, I have tried
-Adding Support Libraries
-Changing the target sdk version from 19 to 18
Please, what am I doing wrong?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apply);
subm = (Button) findViewById(R.id.button1);
fname = (EditText) findViewById(R.id.editText1);
lname = (EditText) findViewById(R.id.editText2);
addr = (EditText) findViewById(R.id.editText3);
city = (EditText) findViewById(R.id.editText4);
state = (EditText) findViewById(R.id.editText5);
zip = (EditText) findViewById(R.id.editText6);
phone = (EditText) findViewById(R.id.editText7);
dob = (EditText) findViewById(R.id.editText8);
email = (EditText) findViewById(R.id.editText9);
ssn = (EditText) findViewById(R.id.editText10);
subm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String httpsURL = "https://example.com/apis/submit_credit_application.php";
String query = "fname="+URLEncoder.encode(fname.getText().toString(),"UTF-8");
query += "&lname="+URLEncoder.encode(lname.getText().toString(),"UTF-8");
query += "&addr="+URLEncoder.encode(addr.getText().toString(),"UTF-8");
query += "&city="+URLEncoder.encode(city.getText().toString(),"UTF-8");
query += "&state="+URLEncoder.encode(state.getText().toString(),"UTF-8");
query += "&zip="+URLEncoder.encode(zip.getText().toString(),"UTF-8");
query += "&phone="+URLEncoder.encode(phone.getText().toString(),"UTF-8");
query += "&dob="+URLEncoder.encode(dob.getText().toString(),"UTF-8");
query += "&email="+URLEncoder.encode(email.getText().toString(),"UTF-8");
query += "&ssn="+URLEncoder.encode(ssn.getText().toString(),"UTF-8");
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
}catch(IOException e){
Toast.makeText(
getApplicationContext(),
(CharSequence) e,
Toast.LENGTH_LONG
).show();
}
}
});
}
here's a Pastebin with my logcat
As your error says you can't run network tasks on the the main thread. AsyncTasks are good for running short tasks that you don't want to block the main thread with.
Link to google docs.
http://developer.android.com/reference/android/os/AsyncTask.html
// This class is just added somewhere in your main activity, like a function.
private class PostFormTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... queryDetails) {
try{
String httpsURL = "https://example.com/apis/submit_credit_application.php";
String query = "fname="+URLEncoder.encode(queryDetails[0],"UTF-8");
query += "&lname="+URLEncoder.encode(queryDetails[1],"UTF-8");
query += "&addr="+URLEncoder.encode(queryDetails[2],"UTF-8");
// Keep adding to your query but instead of getting your details
// from the textview they are in the queryDetails array.
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
}catch(IOException e){
Toast.makeText(
getApplicationContext(),
(CharSequence) e,
Toast.LENGTH_LONG
).show();
}
return false
}
protected void onPostExecute(Long result) {
}
}
Then on your onClick event just have.
new PostFormTask().execute(fname.getText().toString(),
lname.getText().toString() );
// just send your form details to your task here, you will want to add all your details
// from your above code.
Hope that helps.
Alright! since you want you two points. Here is a good tutorial where i call a json web service using AsyncTask in andorid. Basically AsyncTask creates a new thread where network operations can be conducted.

My data goes into my MySQL database, but it still gives a duplicate entry error, while I'm getting the error SingleClientConnManager in java

I'm trying to make a register page for my android app.
I have managed to create a login page and I'm now trying to get the register page to work.
I've managed to get the data I'm sending via the register page into the database. I'm using a php script to transfer the data into my mysql database.
But every time I register, it sends the data and gives the echo back saying that the username/mail already exists.
It also shows this error in Java: Invalid use of SingleClientConnManager: connection still allocated.
I've been trying to fix this for hours but can't find anything that helps.
This is my database:
id - primary key AI
mail - unique
password
username - unique
This is my php script
<?php
$hostname_memolink = "localhost";
$database_memolink = "memolink";
$username_memolink = "android";
$password_memolink ="f3.W2TmM}8yO";
$memolink = mysql_connect($hostname_memolink, $username_memolink, $password_memolink) or trigger_error(mysql_error(), E_USER_ERROR);
mysql_select_db($database_memolink, $memolink);
$mail = $_POST['mail'];
$password = $_POST['password'];
$username = $_POST['username'];
if (trim($password) == "" or trim($username) == "" or trim($mail) == "")
{
echo "variables are null";
exit;
}
else
{
$resultUsername = mysql_query("SELECT * FROM tbl_user WHERE username='$username'");
$resultMail = mysql_query("SELECT * FROM tbl_user WHERE mail='$mail'");
$num_rows_username = mysql_num_rows($resultUsername);
$num_rows_mail = mysql_num_rows($resultMail);
if ($num_rows_username >= 1 && $num_rows_mail >= 1) {
echo "username or email already exists";
die();
}
else
{
mysql_query("INSERT INTO tbl_user (id, mail, password, username) VALUES('', '$mail', '$password', '$username')") or die(mysql_error());
echo "registration complete";
}
}
?>
This is my Java method which sends the data to my php file:
HttpPost httpPost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpClient;
List<NameValuePair> registerData;
public void register(){
try{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://www.memo-link.be/php/register.php");
registerData = new ArrayList<NameValuePair>(2);
EditText mailBox = (EditText) findViewById(R.id.mail_box);
EditText userBox = (EditText) findViewById(R.id.username_box);
EditText passBox = (EditText) findViewById(R.id.password_box);
String mail = mailBox.getText().toString();
String username = userBox.getText().toString();
String password = passBox.getText().toString();
registerData.add(new BasicNameValuePair("mail", mail));
registerData.add(new BasicNameValuePair("username", username));
registerData.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(registerData));
response = httpClient.execute(httpPost); //send data to Internet
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response : " + response.toString());
if (response.equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Username already exists!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Mail address already in use!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("registration complete")){
runOnUiThread(new Runnable(){
public void run(){
Toast toast = Toast.makeText(RegisterActivity.this, "Registration Succesfull", Toast.LENGTH_SHORT);
toast.show();
}
});
startActivity(new Intent(RegisterActivity.this, DashboardActivity.class));
}
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
}catch (Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
Thanks in advance
Please see this, if this might help you. Let us know if you need more help.
Android: Invalid use of SingleClientConnManager: connection still allocated
Also, in your code, you are executing the query twice, which on the first time executes normally and as soon as it gets second query (as your data is already inserted), this satisfies the condition and prints the error message. Hope this will help.

Sending data from fragment to activity and parse json

I am trying to send 'id' from my fragment activity to an activity and parsing json data based on this 'id' field.
I am successfully sending data from fragment to TourDetail activity, but it is not parsing the json based on same 'id'. The code is not reaching second try block as I examined it using toasts.
Although the same activity(TourDetailActivity.java) is working fine when I pass 'id' from some other activity. Say, if I passed 'id' from jsonuseactivity.java, it is received successfully by TourDetailActivity.java and the respective json result is generated and the appropriate result is displayed.
But if the same 'id' is passed from the fragment activity, it is although receiving the 'id' but not generating the json and no required results based on json are being generated.
TourDetailActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_detail);
Intent intent = getIntent();
String rcvid = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(), rcvid, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("tourid", rcvid));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
Toast.makeText(getApplicationContext(), "in try block", Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost(
//"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
"http://www.futurolicht.com/jsontour.php", // in case of a remote server
postParameters);
String result = response.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//parse json data
try {
Toast.makeText(getApplicationContext(), "in 2nd try block", Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tname = (TextView) findViewById(R.id.txt_tourtitle);
td = (TextView) findViewById(R.id.txt_day);
tn = (TextView) findViewById(R.id.txt_night);
tdest = (TextView) findViewById(R.id.txt_tourdetail_dest);
btn = (Button) findViewById(R.id.btn_tourdetail);
btn.setOnClickListener(this);
tname.setText(json_data.getString("tour_name"));
tn.setText(json_data.getString("nights"));
td.setText(json_data.getString("days"));
name = json_data.getString("tour_name");
n = json_data.getString("nights");
d = json_data.getString("days");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
This is my Fragmentone.java's onCreate() method code:
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
String fontPath = "fonts/ox.ttf";
b1 = (Button)root.findViewById(R.id.featured_btn1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id = "34";
Intent intent = new Intent(getActivity(), TourDetailActivity.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}
});
I didn't know what actually happened as above code seems okay to me. Instead of sending data, you can make the variable as Static and access that variable in other class like Fragmentone.id. This will definitely work.
Also did you try to catch that id in onStart() instead of onCreate() ? It is convenient to check if there are arguments passed to the fragment in startup

Categories