I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();
Related
When I try to upload the image and click the submit button, the logcat show out this message.
Logcat Result
2018-10-15 22:21:32.191 22289-22477/com.example.edward.neweventmanagementsystem E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
Java File
package com.example.edward.neweventmanagementsystem;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.Model.EventInfo;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends AppCompatActivity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText, mRegisterEventId;;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
Uri uriImage ;//= Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListOfEvent"); //.push();
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//insert data to database
mRegisterEventId = (EditText) findViewById(R.id.RegisterEventId);
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(CreateEvent.this);
mDialog.setMessage("Please waiting...");
mDialog.show();
int selectedId = mEventType.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String id = mRegisterEventId.getText().toString().trim();
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(id)) {
mRegisterEventId.setError("Enter Event ID!");
return;
}
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter Event Name!");
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Please select type of event type!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Please select event date!");
return;
}
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mRegisterEventId.getText().toString()).exists()) {
mDialog.dismiss();
Toast.makeText(CreateEvent.this, "ID already exists!", Toast.LENGTH_SHORT).show();
}else {
mDialog.dismiss();
EventInfo eventInfo = new EventInfo(mRegisterEventId.getText().toString().trim(),mEventNameText.getText().toString().trim(), mContactNumText.getText().toString().trim(), mEventDate.getText().toString().trim(), radioButton.getText().toString().trim(), mEventLocationText.getText().toString().trim());
mDatabaseReference.child(mRegisterEventId.getText().toString()).setValue(eventInfo);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
final StorageReference storageReference = storage.getReference();
System.out.println(uriImage);
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
// Uri downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().getResult();
// String urlImage = downloadUrl.toString();
mDatabaseReference.child(id).child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
System.out.println(taskSnapshot.getUploadSessionUri().toString());
}
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.neweventmanagementsystem.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent photoPickerIntent = new Intent();
photoPickerIntent .setType("image/*");
photoPickerIntent .setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(photoPickerIntent ,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
Anyone know how to solve this problem. Thanks a lot.
Also that, I also face problem when try to display the message in my apps. There was no problem with other field such as Text, RadioButton, Date, only photo I unable to up the real url.
fyi. currenly the url display in firebase database is the photo storage location
It seems like the user is not signed (authenticated from the Firebase ) .
their is two method to solve the problem
1)authenticate the user using authentication
2)set your rule to public for fire-base real-time database
copy and paste this rule in Firebase real-time database >rule
{
"rules": {
".read": true,
".write": true
}
}
But doing this will make
your security rules are defined as public, so anyone can steal, modify or delete data in your database
The Exception clearly says that you are trying to perform operations without having the user logged in.
You can follow this manuel to authenticate and then perform your operations
https://firebase.google.com/docs/auth/android/password-auth
Why can not I upload files to the server? When I used Log.d to print to the log screen, it reported an error can not connect to 192.168.10.2:8080 although I have asked for permission to the Internet and read the internal memory of the device.
APIUtils.java
import android.provider.ContactsContract;
public class APIUtils {
public static final String Base_Url = "http://192.168.10.2:8080/Quanlysinhvien/";
public static DataClient getData(){
return RetrofitClient.getClient(Base_Url).create(DataClient.class);
}
}
DataClient.java
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface DataClient {
#Multipart
#POST("uploadhinhanh.php")
Call<String> UploadPhot(#Part MultipartBody.Part phto);
}
RetrofitClient.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseurl){
OkHttpClient builder = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.client(builder)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
DangKyActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.APIUtils;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.DataClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Callback;
import retrofit2.Response;
public class DangKyActivity extends AppCompatActivity {
ImageView imgdangky;
EditText edtUsername, edtPassword;
Button btnhuy, btnxacnhan;
int Request_Code_Image = 123;
String realpath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_ky);
anhxa();
imgdangky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, Request_Code_Image);
}
});
btnxacnhan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(realpath);
String file_path = file.getAbsolutePath();
String[] mangtenfile = file_path.split("\\.");
file_path = mangtenfile[0] + System.currentTimeMillis() + "." + mangtenfile[1];
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file_path, requestBody);
DataClient dataClient = APIUtils.getData();
retrofit2.Call<String> callback = dataClient.UploadPhot(body);
callback.enqueue(new Callback<String>() {
#Override
public void onResponse(retrofit2.Call<String> call, Response<String> response) {
if(response != null){
String message = response.body();
Log.d("AAA", message);
}
}
#Override
public void onFailure(retrofit2.Call<String> call, Throwable t) {
Log.d("BBB", "Lỗi " + t.getMessage());
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Request_Code_Image && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
realpath = getRealPathFromURI(uri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imgdangky.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI (Uri contentUri) {
String path = null;
String[] proj = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
path = cursor.getString(column_index);
}
cursor.close();
return path;
}
private void anhxa() {
imgdangky = (ImageView)findViewById(R.id.imageViewDK);
edtPassword = (EditText)findViewById(R.id.editTextDKMK);
edtUsername = (EditText)findViewById(R.id.editTextDKTK);
btnhuy = (Button)findViewById(R.id.buttonHuy);
btnxacnhan = (Button)findViewById(R.id.buttonXacNhan);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I am trying to access my phone's internal storage to attach a file from internal storage. But anyhow I am getting an exception "java.lang.NullPointerException: uri at com.android.internal.util.Preconditions.checkNotNull". I have checked getCount method is not null. But still, i am facing this issue. what do I do?
**Code:**
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
public class User_Issue extends AppCompatActivity {
EditText estoreissue, estorename, edescribe;
Button b, btupload;
RequestQueue requestQueue;
TextView tvupload;
private static final int IMAGE_REQUEST_CODE = 3;
private static final int STORAGE_PERMISSION_CODE = 123;
private ImageView imageView;
private EditText etCaption;
private Uri filePath;
Bitmap bitmap;
int serverResponseCode = 0;
//final String uploadFilePath = "/mnt/Environment.getRootDirectory().getAbsolutePath()/";
//final String uploadFileName = "";
String upLoadServerUri = null;
// Create string variable to hold the Edit\Text Value.
String issue, storename, describe;
// Creating Progress dialog.
ProgressDialog progressDialog;
String HttpUrl = "http://10.238.4.153/user_issue.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__issue);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = (ImageView)findViewById(R.id.imupload);
etCaption = (EditText)findViewById(R.id.etupload);
tvupload = (TextView) findViewById(R.id.tvupload);
estorename = (EditText) findViewById(R.id.editTextstorename);
estoreissue = (EditText) findViewById(R.id.editTextissue);
edescribe = (EditText) findViewById(R.id.editTextdescribe);
b = (Button) findViewById(R.id.button3);
btupload = (Button) findViewById(R.id.buttonupload);
tvupload.setText("Uploading File : 'mnt/Environment.getRootDirectory().getAbsolutePath()/" + "'");
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
requestStoragePermission();
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(User_Issue.this);
progressDialog = new ProgressDialog(User_Issue.this);
btupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v==imageView)
{
Intent in=new Intent();
in.setType("imupload/*");
in.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(in, "Complete action using"), IMAGE_REQUEST_CODE);
}else if(v == btupload){
uploadMultipart();
}
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressDialog.setMessage("Please wait, while we upload your data to server");
progressDialog.show();
GetValueFromEditText();
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing response message coming from server.
Toast.makeText(User_Issue.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(User_Issue.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("storename", storename);
params.put("issue", issue);
params.put("describ", describe);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(User_Issue.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
});
}
// Creating method to get value from EditText.
public void GetValueFromEditText() {
storename = estorename.getText().toString().trim();
issue = estoreissue.getText().toString().trim();
describe = edescribe.getText().toString().trim();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
tvupload.setText("Path: ". concat(getPath(filePath)));
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void uploadMultipart() {
String caption = etCaption.getText().toString().trim();
//getting actual path
String path = getPath(filePath);
//uploading <code>
try {
String uploadID= UUID.randomUUID().toString();
new MultipartUploadRequest(this, uploadID, HttpUrl)
.addFileToUpload(path, "image") //Adding file
.addParameter("caption", caption) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getPath(Uri uri) {
Cursor cursor=null;
cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
//cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}
Logcat:
FATAL EXCEPTION: main
Process: com.example.mi.mikpiadmin, PID: 14255
java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.query(ContentResolver.java:474)
at android.content.ContentResolver.query(ContentResolver.java:434)
at com.example.mi.mikpiadmin.User_Issue.getPath(User_Issue.java:204)
at com.example.mi.mikpiadmin.User_Issue.uploadMultipart(User_Issue.java:187)
at com.example.mi.mikpiadmin.User_Issue$2.onClick(User_Issue.java:101)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
check Access permissions as required
Also make sure to use .checkDirExists() to see file availablity
You should make sure that filePath is not null before using it with getContentResolver().query()
package symca.gescoe.com.sampleparseapp.payment_task;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import symca.gescoe.com.sampleparseapp.R;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.List;
public class PayRent extends Activity {
TextView ownerName, ownerEmail, ownerPropType, ownerLocation, ownerAccountNo, renterAccountNo;
EditText propId;
int confirmFlag = 0;
int rentFinal = 0, mainFinal = 0, totalFinal = 0;
int rent;
int maintenance;
String ownerNameStr;
String ownerEmailStr;
String ownerPropTypeStr;
String ownerLocationStr;
String ownerAccountNoStr;
String renterAccountNoStr;
String propIdStr;
Button btnpayRent;
ImageView btnConfirm;
int payInterestFlag = 1;
ProgressDialog progressDialog;
String proType, location, email, fname, lname, ownerAccount, renterAccount;
String ownerObjId,ownerAvlBal;
int bhk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_rent);
// ParseACL defaultACL = new ParseACL();
// defaultACL.setPublicWriteAccess(true);//------temp
btnConfirm = (ImageView) findViewById(R.id.btnConfirmIDPay);
btnpayRent = (Button) findViewById(R.id.btnPayRent);
propId = (EditText) findViewById(R.id.tvPropIDPay);
ownerName = (TextView) findViewById(R.id.tvNamePay);
ownerEmail = (TextView) findViewById(R.id.tvEmailPay);
ownerPropType = (TextView) findViewById(R.id.tvPropTypePay);
ownerLocation = (TextView) findViewById(R.id.tvLocPay);
ownerAccountNo = (TextView) findViewById(R.id.tvLandAccountNoPay);
renterAccountNo = (TextView) findViewById(R.id.tvRenterAccountNoPay);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLauPropertyPay);
btnConfirm.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
confirmFlag = 1;
progressDialog = ProgressDialog.show(PayRent.this, "Please Wait...", "Property Details Loading..");
String propIdStr = propId.getText().toString();
if (!propIdStr.equals(""))
{
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PostAdd");
query.whereEqualTo("objectId", propIdStr);
query.getFirstInBackground(new GetCallback<ParseObject>()
{
#Override
public void done(ParseObject object, ParseException e)
{
if (e == null)//-----from Post Add Table--------------
{
email = object.getString("PostEmail");
bhk = object.getInt("BHK");
proType = object.getString("PropType");
location = object.getString("Location");
rent = object.getInt("ERent");
maintenance = object.getInt("Emaintainance");
//-------------from User Table-------
ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("email", email);
query.getFirstInBackground(new GetCallback()
{
#Override
public void done(ParseObject object, ParseException e)
{
String interest = object.getString("PaymentInterest");
if (interest.equals("Interested"))
{
payInterestFlag = 0;
fname = object.getString("FirstName");
lname = object.getString("LastName");
ownerAccount = object.getString("AccountNo");
renterAccount = ParseUser.getCurrentUser().getString("AccountNo");
ownerName.setText(fname + " " + lname);
ownerAccountNo.setText(ownerAccount);
renterAccountNo.setText(renterAccount);
ownerEmail.setText(email);
ownerLocation.setText(location);
ownerPropType.setText(bhk + " " + "BHK " + proType);
progressDialog.dismiss();
} else
{
progressDialog.dismiss();
payInterestFlag = 1;
AlertDialog.Builder alertPayInterest = new AlertDialog.Builder(PayRent.this);
alertPayInterest.setTitle("Not Interested!");
alertPayInterest.setIcon(R.drawable.notonline);
alertPayInterest.setMessage("Ohhh!!!\nSelected Add Owner Not Interested In Online Payment");
alertPayInterest.show();
}
}
});
} else
{
progressDialog.dismiss();
propId.setError("Property Id is Not Valid!!!");
}
}
});
}//if
else {
progressDialog.dismiss();
propId.setError("Property Id Blank");
}
}
});
//----------------------------------------------------------------------
btnpayRent.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Click Rent", Toast.LENGTH_SHORT).show();
if ((!propId.getText().toString().equals("")) && (confirmFlag == 1))
{
LayoutInflater factory = LayoutInflater.from(PayRent.this);
final View textEntryView = factory.inflate(R.layout.custom_dialogue_payrent, null);
final EditText inputRent = (EditText) textEntryView.findViewById(R.id.edtRentCustom);
inputRent.setEnabled(false);
final EditText inputMain = (EditText) textEntryView.findViewById(R.id.edtMainCustom);
inputMain.setEnabled(false);
ImageView imgRent = (ImageView) textEntryView.findViewById(R.id.edtImgRentPay);
ImageView imgMain = (ImageView) textEntryView.findViewById(R.id.edtImgMainPay);
// Toast.makeText(getApplicationContext(),"rent is "+rent,Toast.LENGTH_SHORT).show();
inputRent.setText("" + rent);
inputMain.setText("" + maintenance);
imgRent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputRent.setEnabled(true);
//inputRent.requestFocus();
}
});
imgMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputMain.setEnabled(true);
}
});
final AlertDialog.Builder alert = new AlertDialog.Builder(PayRent.this);
alert.setIcon(R.drawable.donation);
alert.setTitle("Payment Details");
alert.setView(textEntryView);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//-------------Positive Button
rentFinal = Integer.parseInt(inputRent.getText().toString());
mainFinal = Integer.parseInt(inputMain.getText().toString());
totalFinal = rentFinal + mainFinal;
//--transaction table-------
ParseObject objTrans = new ParseObject("Transactions");
objTrans.put("Debtor", renterAccount);//renter
objTrans.put("Creditor", ownerAccount);//owner
objTrans.put("TotalAmt", totalFinal);
objTrans.saveInBackground();
//--------------------------------
final ParseQuery<ParseObject> querypradip = ParseQuery.getQuery("Pay");
querypradip.whereEqualTo("AccountNo", ownerAccount);
querypradip.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed."+e.getMessage());
} else {
Log.d("score", "Retrieved the object.");
ownerObjId=object.getObjectId();
ownerAvlBal=object.getString("AvailableBal");
Log.d("Oid", ownerObjId);
Log.d("OBal", ownerAvlBal);
Toast.makeText(getApplicationContext(), "ownerId"+ownerObjId+"\nAval Bal"+ownerAvlBal, Toast.LENGTH_LONG).show();
//--------------------UPDATE--------------
ParseQuery query = new ParseQuery("Pay");
query.getInBackground(ownerObjId, new GetCallback()
{
public void done(final ParseObject object, ParseException e)
{
if (e == null)
{
object.put("Bal", 5000);
object.saveInBackground();
Toast.makeText(getApplicationContext(), "After Save In Back", Toast.LENGTH_LONG).show();
object.saveInBackground(new SaveCallback()
{
public void done(ParseException e)
{
object.put("AvailableBal", 7000);
object.saveInBackground();
}
});
}
else
{
e.printStackTrace();
Log.e("In Update",e.getMessage());
}
}
});
}
}
});
//---reter table---------------
ParseQuery<ParseObject> queryPay = new ParseQuery<ParseObject>("Pay");
queryPay.whereEqualTo("AccountNo", renterAccount);
queryPay.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
String AvailBal = object.getString("AvailableBal");
String renterID = object.getObjectId();
final int remainsBal = Integer.parseInt(AvailBal) - totalFinal;
Log.e("Renter", "************" + remainsBal);
Log.e("RenterID", "************" + renterID);
//----------------Update------------------
ParseQuery queryUpdatePay = new ParseQuery("Pay");
queryUpdatePay.getInBackground(renterID, new GetCallback() {
#Override
public void done(ParseObject Obj, ParseException e) {
if (e == null) {
Obj.put("AvailableBal", "" + remainsBal);
Log.e("Update", "************" + remainsBal);
Obj.saveInBackground();
} else {
// do something with the error...
}
}
});
}//done
});
}
});//Ok
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}
);
alert.show();
} else
if (propId.getText().toString().equals(""))
{
propId.setError("Property Id Blank!");
}
if (confirmFlag == 0)
{
Toast.makeText(getApplicationContext(), "Please Confirm Property Id before Pay", Toast.LENGTH_SHORT).show();
}
}
});
}//OnCreate
}
I am able to store(Simply put using object) data in Pay table as well as also get from table but when I am trying to update it doesn't show any change in table..........
same I am applying for Current User(renter data) it done all get data,update but except current user others users data not update
I do not want to try and understand such a large block of code. In the future please try and boil down the relevant pieces. However:
Looks like you do a query right after saving. Note that saveInBackground() is async, thus it starts (as the name suggests) to contact parse.com and save in a background thread. If the query depend on the object being saved, then you need to wait for it to complete by adding the SaveCallback parameter saveInBackground(new SaveCallback)
If it is because the update fails, then again implement the SaveCallback to see what Exception is thrown saveInBackground(new SaveCallback)
You should never be able to update any other User objects than your own. That would be a huge security issue. A work around could be to create a cloud function using useMasterKey() and call that function from your app.
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.