Android dialog not showing - java

Who would of thought getting a dialog box to show would be so difficult. In C# it is so easy. I've looked all over line for help and every tip seems to cause me trouble than good. Can someone please look at the below code and tell me where I might have gone wrong?
What I want is very simple. User clicks button. Then list appears. Then user clicks on one of the items in list, and dialogue appears. The code in onItemClick in the listview event is from someone else. It apparently works for that person. I keep clicking and seeing nothing. I'm open to suggestions on how to fix it, or new code all together. Sorry, the log has no error messages.
Please be specific about where I put the code as I'm an Android noob. And thank you in advance!
public class SetPrediction extends Activity
{
Button btnInsrt, btnFTeam, btnSTeam;
ArrayList<NameValuePair> nameValuePairs;
TextView txtGameTeams;
Bundle recdData;
String game;
JSONArray jArray;
String result;
InputStream is;
StringBuilder sb;
ArrayList<String> fNames;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.set_prediction);
nameValuePairs = new ArrayList<NameValuePair>();
txtGameTeams = (TextView) findViewById(R.id.txtGameTeams);
recdData = getIntent().getExtras();
game = recdData.getString("xxxx.xxxx.xxx");
txtGameTeams.setText("xxxxxxx: " + game + " game.");
btnInsrt = (Button) findViewById(R.id.btnInsert);
btnFTeam = (Button) findViewById(R.id.btnFirstTeam);
btnSTeam = (Button) findViewById(R.id.btnSecondTeam);
btnFTeam.setText(removeSpaces(game.split("vs")[0]));
btnSTeam.setText(removeSpaces(game.split("vs")[1]));
btnSTeam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("players", removeSpaces(game.split("vs")[1])));
fNames = new ArrayList<String>();
listView = (ListView) findViewById(R.id.lstPlayerForPrediction);
//http post
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/getTeamPlayers.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
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 + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
}
//parse json data
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
fNames.add(jArray.getJSONObject(i).getString("First_Name"));
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SetPrediction.this, android.R.layout.simple_list_item_1, fNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View predictView, int item, long arg3)
{
final CharSequence[] items = {"Online", "Away", "Do not distrub","Invisible","Offline"};
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this);
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
public String removeSpaces(String s)
{
StringTokenizer st = new StringTokenizer(s," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
return t;
}
The problem is in the listView.setOnItemClickListener(new OnItemClickListener() event. That the part that doesn't work.

Check out this:
public void showAlertDialog(String title, String message, Context context)
{
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}

Try using these code instead of your code just a minor change:::
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this).create();
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.show();
also import the following :::
import android.app.AlertDialog;
import android.content.DialogInterface;

Related

How to parse data from one activity to another

Can anyone help me with this. I want to send data from edittext to another activity in the JSONMessage. I want to send to the IDDevice in my second activity.
Here is my code
It's my firstActivity
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.bAdd);
lv = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
onButtonClick();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String inputID = et.getText().toString();
Intent IDdevice = new Intent(MainActivity.this, ControlLed.class);
IDdevice.putExtra("ID", inputID);
startActivity(IDdevice);
}
});
}
And second activity
public void device1on(){
String topic = "server/esp001";
MqttMessage message = new MqttMessage();
message.setPayload("{\"idDevice\":\"esp001\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}".getBytes());// I want to send data from first activity to the idDevice
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
In second activity, get id from Intent using getStringExtra method as mentioned below:
String id = getIntent().getStringExtra("ID");
And then set it to message object
JSONObject json = new JSONObject();
try {
json.put("idDevice", id);
json.put("status", "0");
json.put("data", "100");
json.put("address", "1");
json.put("function", "1");
json.put("user", "admin");
} catch (JSONException e) {
}
String payload = json.toString(); //"{\"idDevice\":\"value of id\",\"status\":\"0\",‌​\"data\":\"100\",\"a‌​ddress\":\"1\",\"fun‌​ction\":\"1\",\"user‌​\":\"admin\"}"
message.setPayload(payload.getBytes());
String getvallue;
Intent i=i.getIntent();
getVallue=i.getStringExtra("name");
Textview txt=(Textview)findviewbyid(R.id.txt);
txt.setText(getVallue);

how to add data in list view from background class

I am getting this exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page2);
lv = (ListView) findViewById(R.id.list_view);
btnNew = (Button)findViewById(R.id.btnAddNew);
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
moveToNewUser.putExtra("ClickType","1");
startActivity(moveToNewUser);
}
});
new Connection2().execute();
// Listview Data
}
private class Connection2 extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
test2();
return null;
}
#Override
protected void onPostExecute(Object s) {
super.onPostExecute(s);
}
}
public void test2() {
HttpURLConnection connection = null;
try {
sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);
String storedUUID = sharedpreferences.getString("UUID", "");
String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
//String url = "http://crm.xqicai.com/sales/login";
URL postUrl = new URL(url2);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编�,�则中文乱�
while (true) {
String str = reader.readLine();
if (str == null) {
break;
}
System.out.println(str);
JSONObject mainObject = new JSONObject(str);
Status = mainObject.getString("status");
int j=0;
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
else
{
JSONObject mainObject2 = new JSONObject(str);
errorMsg = mainObject2.getString("msg");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
I'm only a beginner, so please forgive me for asking possibly a stupid question.
What line is giving the error? The problem is that you update a view created in the main thread, in your AsyncTask (a different thread). You should update this view in the onPostExecute of your AsyncTask (this is done in your main thread). I don't see immediately where you update the view.
EDIT:
Your problem should be solved if you put these two lines
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
below this line:
lv = (ListView) findViewById(R.id.list_view);
or in the:
protected void onPostExecute(Object s)
Test that:
ListView lv...
lv.post(new Runnable() {
#Override
public void run() {
//Update UI;
lv.setAdapter(...);
}
})
you can try use Handler with sendEmptyMessage() inside asynctask to pass by exception.
ex.
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message inputMessage) {
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
});
note for code bellow:
//call mHandler.sendEmpyMessage() in asynctask:
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action

Android - How to get specific data from URL/JSON?

So I have this code, which is a page with a ListView search field and a button to confirm the search, when the button is pressed the ListView is filled with movie names from the Rotten Tomatoes API, The problem is that someone helped me with this code, and I would love some help breaking it down and understanding it sentence after sentence, My main goal is to get is to get the "title", "synopsis" and "url image" of a movie that was clicked in the list, and pass it with an intent to my other activity but the whole JSON and get specific data stuff, got me very confused.
Link to Rotten Tomatoes API documentation, this is my code:
public class MovieAddFromWeb extends Activity implements View.OnClickListener,
OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
see the modified code below..
public class MovieAddFromWeb extends Activity implements View.OnClickListener, OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
//added new variables
public List<String> movieSynopsis;
public List<String> movieImgUrl;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
//newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl= new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString(#add the synopsis var name returned by the JSON));
movieImgUrl.add(movie.getString(#add the urlvar name returned by the JSON));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
//newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}

Android, how to display a dialog from error of a try catch?

In my app I connect to a website to collect some information at start with a AsyncTask, using a try catch, from here I can display in my catlog the error if any at connection, but I have been trying with out luck to show a dialog displaying the connection failure with options to reconnect or quit, please check my code and tell me what I'm doing wrong or an idea of how to accomplish this
//this is our download file asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsiteaddress");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(webs, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
webs.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
webResult resultRow = new webResult();
//infotodownload
arrayOfWebData.add(resultRow);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
//our progress bar settings
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Conectando al Servidor");
mProgressDialog.setMessage("Cargando informacion...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
EDIT:
then I have try adding the next code as of suggested by Arun
catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
return "ERROR_IN_CODE";
}
return null; // if I place here return "ERROR_IN_CODE" it calls the dialog but it gets always called so I don't need it here
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
if(unused.equals("ERROR_IN_CODE")){ //I get a system crash here!
errornote();
}
}
}
public void errornote() {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("No se a podido descargar la informacion de los medios, deseas reintentarlo, o salir?").setCancelable(false)
.setPositiveButton("Conectar de Nuevo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new DownloadFileAsync().execute();
}
})
.setNegativeButton("Salir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
finish();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Error en la Conexion!");
// Icon for AlertDialog
alert.setIcon(android.R.drawable.ic_dialog_alert);
alert.show();
}
but not working either, my app crashes in the if statement line in onPostExecute. I still need help.
Since you are returning a String object from the protected String doInBackground(String... aurl) return some custom Error String from the catch block and access it in the protected void onPostExecute(String unused). Check if the returned String object is the Custom Error String and show the dialog in protected void onPostExecute(String unused) but only after dismissing the progressDialog i.e. after this line dismissDialog(DIALOG_DOWNLOAD_PROGRESS); show the error dialog.
EDIT
When the control enters the Catch block return some simple String like the one you used "ERROR_IN_CODE".
catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
return "ERROR_IN_CODE";
}
And in the onPostExecute(String unused) check for the following
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
if(unused != null && unused.equals("ERROR_IN_CODE")){
showDialog(SOME_DIALOG_TO_SHOW_ERROR);
}
}
Try calling your activities runOnUiThread() method
activity.runOnUiThread(new Runnable() {
public void run() {
//your alert dialog builder here
});
you are not using the builder to create AlertDialog
remove the line builder.show() and add
AlertDialog alert = builder.create();
alert.show();
I will also recommend that do the UI updates through progressUpdate() or preExecute() and 'postExecute()' of the asyc task.
Implementation
#ReactMethod
public void showCustomAlert(String msg){
final String message = msg;
this.reactContext.runOnUiQueueThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder myDialogBox = new AlertDialog.Builder(reactContext.getCurrentActivity());
myDialogBox.setTitle(Html.fromHtml("<font color='#0037FF'>Konnect</font>"));
myDialogBox.setMessage(message);
myDialogBox.setCancelable(true);
myDialogBox.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog alertDialog = myDialogBox.create();
if (Build.VERSION.SDK_INT <= 23) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
}
alertDialog.show();
WindowManager.LayoutParams wmlp = alertDialog.getWindow().getAttributes();
wmlp.gravity = Gravity.TOP | Gravity.LEFT;
wmlp.x = 25; //x position
wmlp.y = 450; //y position
wmlp.height = 380;
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
});
}

android java run activity without restarting it

I created simple application which would login to DB and get data from it. But now I found a problem: If you in the first time write wrong login data and try to login second time it won't work. You have to restart it.
I think there is a problem in this code: EDITED
public class MyMoodleApplicationActivity extends Activity {
/** Called when the activity is first created. */
EditText username;
EditText password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
final Button loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(loginListener);
final Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(clearListener);
}
private OnClickListener loginListener = new OnClickListener(){
public void onClick(View v){
String usr = username.getText().toString();
String psw = password.getText().toString();
System.out.println("Username: "+usr);
System.out.println("Password: "+psw);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/*****");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
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 + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String usernameFromDB = "";
String firstnameFromDB = "";
String lastnameFromDB = "";
String emailFromDB = "";
String phoneFromDB = "";
String skypeFromDB = "";
String cityFromDB = "";
String descriptionFromDB = "";
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
usernameFromDB = json_data.getString("username");
firstnameFromDB = json_data.getString("firstname");
lastnameFromDB = json_data.getString("lastname");
emailFromDB = json_data.getString("email");
phoneFromDB = json_data.getString("phone1");
skypeFromDB = json_data.getString("skype");
cityFromDB = json_data.getString("city");
descriptionFromDB = json_data.getString("description");
System.out.println(usernameFromDB+ " " + firstnameFromDB+" "+lastnameFromDB+" "
+ emailFromDB + " " + phoneFromDB +" " + skypeFromDB+ " " + cityFromDB + " "+
descriptionFromDB);
}
}
catch(JSONException e){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Toks vartotojas neegzistuoja");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
Log.e("log_tag", "Error parsing data "+e.toString());
}
if(usr.length()== 0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slapyvardžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if(psw.length()==0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slaptažodžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if (usr.equals(usernameFromDB)){
Intent in = new Intent(getApplicationContext(), LoggedUser.class);
in.putExtra("firstname", firstnameFromDB);
in.putExtra("lastname", lastnameFromDB);
in.putExtra("email", emailFromDB);
in.putExtra("phone1", phoneFromDB);
in.putExtra("skype", skypeFromDB);
in.putExtra("city", cityFromDB);
in.putExtra("description", descriptionFromDB);
startActivity(in);
finish();
}
}};
private OnClickListener clearListener = new OnClickListener(){
#Override
public void onClick(View v){
username.setText("");
password.setText("");
}
};
In these if statements I check if username and password you enter is empty username is not equal to the one in database.
How to rewrite the code that it would work?
Edited:
I have user john in DB but if I write John in login field and press login button it won't say that there is not the John user. And in LogCat I see that json stream is readed. Is there a way to set up a rule that upercase and lowercase letters would be different?

Categories

Resources