((Dialog issue ))android.view.WindowManager$BadTokenException: - android

In my Application I need to call a function(Which update the valuesof textviews),I need to call this function inside AlertDialg when OK button is pressed.
the issue is how i can call RefreshData.execute() after ok button of dialog is pressed ?
this is one of the Errors :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.details);
Bundle extras = getIntent().getExtras();
if (extras != null) {
x = extras.getString("key").toString();
} else {
Toast.makeText(getBaseContext(), "null", 0).show();
}
tv_summary = (TextView) findViewById(R.id.tv_summary);
tv_servings_result = (TextView) findViewById(R.id.tv_servings_result);
tv_calories_result = (TextView) findViewById(R.id.tv_calories_result);
tv_fat = (TextView) findViewById(R.id.tv_fat);
tv_monofat = (TextView) findViewById(R.id.tv_monofat);
tv_satfat = (TextView) findViewById(R.id.tv_satfat);
tv_ch = (TextView) findViewById(R.id.tv_ch);
tv_sug = (TextView) findViewById(R.id.tv_sug);
new LoadDetails().execute();
Button MealSize = (Button) findViewById(R.id.btn_size);
MealSize.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
show();
Toast.makeText(getBaseContext(), F + "", 0).show();
}
});
}
void Refresh() {
new RefreshData().execute();
}
void show() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
F = Float.parseFloat(input.getText().toString());
new RefreshData().execute();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
private class RefreshData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(getBaseContext(), "",
" Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
this.progressDialog.dismiss();
tv_servings_result.setText(servings_result + "" + F);
tv_calories_result.setText(cal + "g");
tv_fat.setText(ff + "");
tv_monofat.setText(mm + "");
tv_satfat.setText(sasa + "");
tv_ch.setText(chch + "");
tv_sug.setText(sugar + "");
} catch (Exception e) {
Log.e("log_tag",
"Eraaaaaaaaaaaaaaaaaaa connection" + e.toString());
}
}
#Override
protected Void doInBackground(Void... params) {
try {
sugar = Float.valueOf(sug).floatValue();
sugar *= F;
cal = Float.valueOf(calories_result).floatValue();
cal *= F;
ff = Float.valueOf(fat).floatValue();
ff *= F;
mm = Float.valueOf(monofat).floatValue();
mm *= F;
} catch (Exception e) {
Log.e("log_tag",
"Eraaaaaaaaaaaaaaaaaaa connection" + e.toString());
}
return null;
}
}
}

instead using
this.progressDialog = ProgressDialog.show(getBaseContext(), ""," Loading...");
try with
this.progressDialog = ProgressDialog.show(yourActivity.this, ""," Loading...");

Related

If Recyclerview scroll then item id change how to resolve?

public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, int index) {
holder = holder1;
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder.txtBookBookDateOFIssue.setText(pdfList.getType());
holder.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder.txtDownload.setVisibility(View.VISIBLE);
holder.layout_download_note_option.setVisibility(View.GONE);
} else {
holder.txtDownload.setVisibility(View.GONE);
holder.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
/* alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", pdfList.getFileName());
intent.putExtra("from", "url");
intent.putExtra("getSubjectName", pdfList.getSubjectName());
context.startActivity(intent);
}
});*/
alertDialog.show();
}
}
});
holder.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) !=-1) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
}
}
this is my adapter class
I have a RecyclerView. Each row has a Download button, Cancale button, and Progressbar. when click on the Download button have to Download PDF from my phone storage and have to progress Progressbar The problem is when I scroll down the recyclerview the change item Id .means I can fit 1 items on the screen at once.then scroll ItemId change

FAILED BINDER TRANSACTION,but there is nothing in intent

I have a failed binder transaction error when the app quits abnormally,but there is nothing in intent.
The images of every xml are lower than 40K,so I think it's not the problem of images.
This is my code.
... ...
public class MainActivity extends Activity implements OnClickListener{
private SlideMenu slideMenu;
static Socket socket;
private TextView titleName;
private RelativeLayout container;
private Map<String, String> mainleft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainleft = new LinkedHashMap<String, String>();
titleName = (TextView)findViewById(R.id.title_bar_name);
container = (RelativeLayout)findViewById(R.id.container);
slideMenu = (SlideMenu) findViewById(R.id.slide_menu);
ImageView menuImg = (ImageView) findViewById(R.id.title_bar_menu_btn);
menuImg.setOnClickListener(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String IMEI = telephonyManager.getDeviceId();
System.out.println("IMEIļ¼š" + IMEI);
try {
FragmentViewall fragment1 = new FragmentViewall(getBaseContext(),"zhuxitong.xml");
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText((CharSequence) "zhuxitong");
container.setBackgroundColor(Color.WHITE);
InputStream input = getResources().getAssets().open("mainleftcfg.xml");
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(input, "UTF-8");
int event = pullParser.getEventType();
String[] temp = null;
while (event != XmlPullParser.END_DOCUMENT)
{
switch (event)
{
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if("item".equals(pullParser.getName()))
{
temp = new String[2];
}
if ("name".equals(pullParser.getName()))
temp[0] = new String(pullParser.nextText());
if ("xmlname".equals(pullParser.getName()))
temp[1] = new String(pullParser.nextText());
break;
case XmlPullParser.END_TAG:
if("item".equals(pullParser.getName()))
{
mainleft.put(temp[0], temp[1]);
temp = null;
}
break;
}
event = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
initView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.title_bar_menu_btn:
if (slideMenu.isMainScreenShowing()) {
slideMenu.openMenu();
} else {
slideMenu.closeMenu();
}
break;
}
}
private int initView()
{
new Thread() {
public void run() {
String serverIP = LoginActivity.socketipValue;
String serverDK = LoginActivity.socketdkValue;
try {
socket = new Socket(serverIP, Integer.parseInt(serverDK));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
View line = new View(this);
line.setBackgroundResource(R.drawable.ic_shelf_category_divider);
Drawable drawable= getResources().getDrawable(R.drawable.ic_category_mark2);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.leftq);
Iterator iter = mainleft.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
final String temp = (String)entry.getValue();
final String temp2 = (String)entry.getKey();
TextView textt = new TextView(this);
textt.setText((CharSequence) entry.getKey());
textt.setTextColor(Color.WHITE);
textt.setTextSize(18);
textt.setGravity(Gravity.CENTER);
textt.setBackgroundResource(R.drawable.selector_category_item);
textt.setCompoundDrawables(drawable,null,null,null);
textt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
FragmentViewall fragment1 = new FragmentViewall(getBaseContext(), temp);
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText((CharSequence) temp2);
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(textt);
}
TextView texttv = new TextView(this);
texttv.setText(getResources().getString(R.string.g6c1_video));
texttv.setTextColor(Color.WHITE);
texttv.setTextSize(18);
texttv.setGravity(Gravity.CENTER);
texttv.setBackgroundResource(R.drawable.ic_item_selected_bg);
texttv.setCompoundDrawables(drawable,null,null,null);
texttv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
videoontimeFragment fragment1 = new videoontimeFragment();
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText(getResources().getString(R.string.g6c1_video));
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(texttv);
TextView texttb = new TextView(this);
texttb.setText(getResources().getString(R.string.g6c2_video));
texttb.setTextColor(Color.WHITE);
texttb.setTextSize(18);
texttb.setGravity(Gravity.CENTER);
texttb.setBackgroundResource(R.drawable.ic_item_selected_bg);
texttb.setCompoundDrawables(drawable,null,null,null);
texttb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
videobackFragment fragment1 = new videobackFragment();
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText(getResources().getString(R.string.g6c2_video));
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(texttb);
TextView textt = new TextView(this);
textt.setText(getResources().getString(R.string.action_loginout));
textt.setTextColor(Color.WHITE);
textt.setTextSize(18);
textt.setGravity(Gravity.CENTER);
textt.setBackgroundResource(R.drawable.selector_category_item);
textt.setCompoundDrawables(drawable,null,null,null);
textt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LoginActivity.sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
LoginActivity.sp.edit().clear().commit();
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
MainActivity.this.startActivity(intent);
MainActivity.this.finish();
slideMenu.closeMenu();
}
});
linearLayout.addView(textt);
TextView textt2 = new TextView(this);
textt2.setText(getResources().getString(R.string.action_settings));
textt2.setTextColor(Color.WHITE);
textt2.setTextSize(18);
textt2.setGravity(Gravity.CENTER);
textt2.setBackgroundResource(R.drawable.selector_category_item);
textt2.setCompoundDrawables(drawable,null,null,null);
textt2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("1.0");
builder.setPositiveButton("Confirm",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
slideMenu.closeMenu();
}
});
linearLayout.addView(textt2);
return 0;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
dialog();
return true;
}
return true;
}
protected void dialog() {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("Quit?");
builder.setTitle("tips");
builder.setPositiveButton("Confirm",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNegativeButton("Cancel",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

how to make a view visible from customAdapter's textView's ClickEvent in android?

I have made an activity In that I am having three relative Layouts and i am making them visible and gone as per needed.Now I have one ListView Called BuyingRequestList and for that i have made customeAdapter ,Now I have put a clickEvent of CustomAdapter's textView,Now what i need is when I click on the ListItem's textView "Quote" one relative layout "quote_view" is only visible and other two layouts should be invisible,My code is as below:
BuyingRequest.java
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
ImageView iv_fav_menu;
private int flag = 1;
ScrollView scr_post;
RelativeLayout scr_view;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
JSONObject jsonObj;
JSONArray requestes = null;
ArrayList<HashMap<String, String>> reqList;
private BuyingRequestAdapter buyingRequestContent;
RelativeLayout rl_botm;
ListView lv;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
header.back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
new GetBuyingReqList().execute();
scr_view.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pro_cat:
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
#Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
#Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
new postBuyingReqList().execute();
break;
case R.id.iv_img:
showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");
break;
}
}
#SuppressWarnings("deprecation")
private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
final Dialog dialog = new Dialog(BuyingreqActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialog.setContentView(R.layout.popup_alert);
dialog.setCancelable(false);
final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);
final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_rgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
System.out.println("=========== perform click ==============");
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
System.out.println(" PATH ::: " + imageUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
dialog.dismiss();
}
});
btn_lft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
quoteList = (ListView) findViewById(R.id.quote_list);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* getting qoute List...!!!
*/
private class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* post Buying Request api()...!!!
*/
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
// Creating service handler class instance
postURL = postURL.replace(" ", "%20");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
flag = 0;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i;
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 0) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
} else {
Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
}
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) { // for camera
try {
System.out.println("============= FILENAME :: " + fileName);
if (new File(Const.DIR_USER + "/" + fileName).exists()) {
performCrop();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // for crop image
try {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);
// pro_pic.setImageBitmap(thePic);
#SuppressWarnings("deprecation")
Drawable dra = (Drawable) new BitmapDrawable(thePic);
proImg.setImageDrawable(dra);
proImg.setScaleType(ScaleType.FIT_XY);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data != null) {
/*
* fileName = Const.DIR_USER + "/" + "user_" +
* Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
* "_" + System.currentTimeMillis() + ".png";
*/
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
Bundle extras2 = data.getExtras();
Bitmap photo = extras2.getParcelable("data");
Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
ImageView picView = (ImageView) findViewById(R.id.iv_img);
picView.setImageBitmap(photo);
}
}
}
private void performCrop() {
try {
System.out.println("============= AFTER FILENAME :: " + fileName);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 200);// 256
cropIntent.putExtra("outputY", 200);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
Adaptrer.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* new (BuyingreqActivity)GetQuoteList.execute();*/
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
Create an interface class, say ViewHider
public interface ViewHider{
public void hideView(String clickedtext);
}
have your activity implement this.
In your activity add unimplemented method and write inside it like
#Override
public void hideView(String clickedtext) {
if(clickedtext.equals("Quote"){
layoutName.setVisibility(View.GONE);
}
}
In your adapter, create an object of ViewHider class
ViewHider viewHider;
then, set click listener for the text view you want and inside that call the method
if(textView.getText.equals("Quote")
viewHider.hideView("Quote");

android textview does not show after setting visible from another thread

I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);

Categories

Resources