I'm trying to display read from table in database, what i have written so far passes the json, however rather than showing in textview - it displays as a short popup, and then disappears.
Activity_tasks.java
package com.example.myapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class activity_tasks extends AppCompatActivity {
TextView TextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button button = findViewById(R.id.button1);
button.setOnClickListener(v -> showInfo());
TextView = findViewById(R.id.textView4);
downloadJSON();
}
private void downloadJSON() {
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
setTextView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://myurl.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void setTextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
}
}
private void showInfo() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setIcon(R.drawable.alert);
builder.setTitle(" ");
builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");
// Create and show the AlertDialog
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
I have a funny feeling this is something about me having a button requesting a pop-up too in the code, perhaps I haven't integrated the 2nd onCreate properly?
The above is linked to a textview on activity_tasks.xml
Example on phone:
activity.xml below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:clickable="true"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:focusable="true">
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="95dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.946"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="#drawable/shortlogo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/button"
android:layout_width="158dp"
android:layout_height="153dp"
android:background="#drawable/circlebutton"
android:text="#string/hit_me_again"
android:textColor="#000"
android:textSize="8sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.896" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/alert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="183dp"
android:layout_height="119dp"
android:textColor="#color/white"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/design"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.092"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/version_0_0_1"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.963"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What you are seeing at the bottom is the toast you create in onPostExecute(). You receive the data, but then never update the text of the TextView. In setTextView() you could also do that:
textView.setText(json);
On another note: Don't use AsyncTasks anymore. They are deprecated and way too laborious. Also, to read the Json much more easily, you can use a library like Gson or Moshi.
Related
my textview in activity configure disappears after setting it
the small text 192.168.0, is the text view appears only when i hit the save button
the textview is disappearing completely when i come back to this activity
edit: added my java code and my xml
package com.example.smartcharge;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class configure extends AppCompatActivity {
EditText ip, port;
public TextView tv;
Button SAVEBTN;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String IPSTR = "ipKey";
public static final String PORTSTR = "portKey";
public static final String TEXT1 = "textkey";
private String text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
ip = findViewById(R.id.et1);
port = findViewById(R.id.et2);
SAVEBTN = findViewById(R.id.savebtn);
tv = findViewById(R.id.tv2);
SAVEBTN.setOnClickListener(v -> {
senddata();
});
loaddata();
updateviews();
}
public void senddata(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(configure.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
String ipstr = ip.getText().toString();
String portstr = port.getText().toString();
tv.setText(ipstr + "," + portstr);
editor.putString(IPSTR, ipstr);
editor.putString(PORTSTR, portstr);
editor.putString(TEXT1, tv.getText().toString());
editor.apply();
Toast.makeText(configure.this,"saved",Toast.LENGTH_LONG).show();
}
public void loaddata(){
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
text1 = sharedPreferences.getString(TEXT1 , "");
}
public void updateviews(){
tv.setText(text1);
}
}
Below is xml code of my configure activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".configure">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broker Settings"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.361"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.038" />
<TextView
android:id="#+id/tv2"
android:layout_width="327dp"
android:layout_height="49dp"
android:text="TextView"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.309"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.247" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btns"
android:text="save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.08"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.572" />
<EditText
android:id="#+id/et2"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:backgroundTint="#D1D1D1"
android:hint="port "
android:inputType="number"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.444">
</EditText>
<EditText
android:id="#+id/et1"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:backgroundTint="#D1D1D1"
android:hint="ip Address"
android:inputType="number"
android:text="192.168.0."
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.163"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.339">
</EditText>
</androidx.constraintlayout.widget.ConstraintLayout>
any one have any clue of this behavior?, please help me if you can :)
The text disappears since the updating of your TextView takes place in onCreate.
#Override
protected void onResume() {
SAVEBTN.setOnClickListener(v -> {
senddata();
});
loaddata();
updateviews();
}
This should do the trick.
Go through the Activity lifecycle to see how this works. But basically moving methods to onResume should work.
I want to show logo from json but it doesn't work. Check my code and inform me about the bug. Else app name and description working fine. They only problem is that it now showing logo. Json is passing the link of that logo. I also use Glide but it doesn't work for me. I done all thing to fix it but i am unable for fix it. All code related to this is below. Please have a look at it
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class BrandshaperActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brandshaper);
new ParseTask().execute();
}
private class ParseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
#Override
protected String doInBackground(Void... params) {
try {
String $url_json = "https://myapi.ga";
URL url = new URL($url_json);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
Log.d("FOR_LOG", resultJson);
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
final ListView lView = (ListView) findViewById(R.id.lvMain);
String[] from = {"app_name","desc","app_logo"};
int[] to = {R.id.app_name,R.id.desc,R.id.app_logo};
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashmap;
try {
JSONObject json = new JSONObject(strJson);
JSONArray jArray = json.getJSONArray("offers");
for (int i = 0; i < jArray.length(); i++) {
JSONObject friend = jArray.getJSONObject(i);
String appname = friend.getString("name");
String description = friend.getString("description");
String applogo = friend.getString("icon");
Picasso.get().load(arrayList.get(position).getThumbnailUrl(applogo)).into(app);
hashmap = new HashMap<String, String>();
hashmap.put("app_name", "" + appname);
hashmap.put("desc", "" + description);
arrayList.add(hashmap);
}
final SimpleAdapter adapter = new SimpleAdapter(BrandshaperActivity.this, arrayList, R.layout.brandshaper_item,from , to);
lView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFF"
android:gravity="left">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_marginLeft="4dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/app_logo"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingStart="3dp"
android:src="#drawable/img_bigcash">
</ImageView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenirblack"
android:text="BigCash"
android:gravity="center"
android:textColor="#color/black"
android:textSize="18dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat_regular"
android:text="Install & Sign up to 200 coins"
android:gravity="center"
android:textColor="#color/black"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="end">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/arrow"></ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvMain"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</RelativeLayout>
I keep getting this error whenever I run the application, which crashes every time I interact with it. The problem first occurred after I moved the original TextView around and altered the color and Font Style. I'm not sure why it's happening now, but it didn't happen before. I'm not exactly sure why this error is occurring either. Please help.
Below is the error message:
E/TypefaceCompatApi26Impl: Unable to collect necessary methods for class java.lang.NoSuchMethodException
java.lang.NoSuchMethodException: android.graphics.FontFamily.<init> []
This is the MainActivity class:
package com.example.exploreroptimizer;
import android.app.ActivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final Cleaner cleaner = new Cleaner();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cleanButton = findViewById(R.id.cleanButton);
final ProgressBar cleanBar = findViewById(R.id.progressBar);
final TextView progressUpdate = findViewById(R.id.progressUpdate);
System.out.println("success");
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread thread = new Thread() {
#Override
public void run() {
try {
final ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
final double a = mi.availMem / 0x100000L;
cleanBar.setProgress(20);
progressUpdate.setText("Cleaning Ram!");
Thread.sleep(1500);
cleanBar.setProgress(40);
progressUpdate.setText("Closing Unused Apps!");
Thread.sleep(1500);
cleanBar.setProgress(100);
progressUpdate.setText("Clearing Cache!");
Thread.sleep(1500);
Cleaner.deleteCache(getApplicationContext());
cleaner.killBackgroundProcesses(getApplicationContext(), getApplicationContext().getPackageManager());
cleaner.clearRAM();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "I have closed " + Cleaner.i + " apps, ", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
}
}
};
thread.start();
}
});
}
}
And this is the xml file code for the UI:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/cleanButton"
android:layout_width="172dp"
android:layout_height="166dp"
android:background="#drawable/cleanbutton"
android:fontFamily="sans-serif"
android:text="Clean"
android:textColor="#FFFFFF"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="312dp"
android:layout_height="382dp"
android:indeterminate="false"
android:max="0"
android:progress="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/progressUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:text="TextView"
android:textColor="#0DB344"
android:textSize="18sp"
android:textStyle="normal|bold"
android:typeface="sans"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/progressBar" />
</androidx.constraintlayout.widget.ConstraintLayout>
This question already has answers here:
Unable to start activity ComponentInfo.....java.lang.IllegalStateException: Already attached
(2 answers)
Closed 3 years ago.
This is my code. Please check.. When I execute it the app crashes. So app was fine before, but I added validation to the form and since then as soon as the app run it crashes. I have used https://www.simplifiedcoding.net/android-form-validation-tutorial/ for adding awsomeform and so I have also made some changes to the strings.xml file. Please check this once too. It was fine before and I could access the file pretty easily.
This is the error I get on Android studio when I try to run the app and the app installs, launches and then crashes.
This is my mainactivity code. I believe something is going on with the implements part and the code i.e. import.com.google.common.collect.range is also unused
MainActivity.java
import android.Manifest;
import android.net.sip.SipSession;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import android.util.Patterns;
import android.widget.EditText;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.google.common.collect.Range;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public Button btn;
public ImageView imageview;
public static final String IMAGE_DIRECTORY = "/demonuts";
public int GALLERY = 1, CAMERA = 2;
public EditText r_name_fill, r_email_fill, r_edit_phone, r_cardetails, r_pass_fill;
public RadioButton r_male, r_female;
public Button r_submit;
public AwesomeValidation awesomeValidation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestMultiplePermissions();
btn = (Button) findViewById(R.id.btn);
imageview = (ImageView) findViewById(R.id.iv);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing awesomevalidation object
/*
* The library provides 3 types of validation
* BASIC
* COLORATION
* UNDERLABEL
* */
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
//initializing view objects
r_name_fill = (EditText) findViewById(R.id.r_name_fill);
r_email_fill = (EditText) findViewById(R.id.r_email_fill);
r_edit_phone = (EditText) findViewById(R.id.r_edit_phone);
r_cardetails = (EditText) findViewById(R.id.r_cardetails);
r_pass_fill = (EditText) findViewById(R.id.r_pass_fill);
r_male = (RadioButton) findViewById(R.id.r_male);
r_female = (RadioButton) findViewById(R.id.r_female);
r_submit = (Button) findViewById(R.id.r_submit);
//adding validation to edittexts
awesomeValidation.addValidation(this, R.id.r_name_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);
awesomeValidation.addValidation(this, R.id.r_email_fill, Patterns.EMAIL_ADDRESS, R.string.emailerror);
awesomeValidation.addValidation(this, R.id.r_pass_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.passworderror);
awesomeValidation.addValidation(this, R.id.r_edit_phone, "^[2-9]{2}[0-9]{8}$", R.string.mobileerror);
awesomeValidation.addValidation(this, R.id.r_name_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.carerror);
r_submit.setOnClickListener(this);
btn.setOnClickListener(this);
}
#Override
public void onClick(View V) {
if (V== r_submit) {
submitForm();
}
showPictureDialog();
}
public void submitForm() {
//first validate the form then move ahead
//if this becomes true that means validation is successfull
if (awesomeValidation.validate()) {
Toast.makeText(this, "Validation Successful", Toast.LENGTH_LONG).show();
//process the data further
}
}
public void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
public void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
public void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView3"
android:layout_width="383dp"
android:layout_height="563dp"
android:contentDescription="#string/todo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/ic_launcher_foreground" />
<TextView
android:id="#+id/r_name"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:layout_marginTop="16dp"
android:text="Name"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/r_name_fill"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:ems="10"
android:hint="John Doe"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView3"
app:layout_constraintHorizontal_bias="0.362"
app:layout_constraintStart_toEndOf="#+id/imageView3"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.003" />
<TextView
android:id="#+id/r_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:text="Email"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.11" />
<EditText
android:id="#+id/r_email_fill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:hint="email#techmahindra.com"
android:inputType="textEmailAddress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.092" />
<TextView
android:id="#+id/r_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone No."
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.05"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.191" />
<EditText
android:id="#+id/r_edit_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="+91-XXXXXX"
android:inputType="phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.174" />
<TextView
android:id="#+id/r_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.256" />
<RadioButton
android:id="#+id/r_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="400dp"
android:text="Male"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.476"
app:layout_constraintStart_toStartOf="parent" />
<RadioButton
android:id="#+id/r_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.315" />
<TextView
android:id="#+id/r_car"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Details"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.059"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.375" />
<EditText
android:id="#+id/r_cardetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Car Details"
android:inputType="text|textMultiLine|textLongMessage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.385" />
<TextView
android:id="#+id/r_dl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Driving Licence"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.071"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.476" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="223dp"
android:layout_marginEnd="16dp"
android:text="Select or Capture Image"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/iv"
android:layout_width="154dp"
android:layout_height="86dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="126dp"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
</RelativeLayout>
<TextView
android:id="#+id/r_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.003"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.844" />
<EditText
android:id="#+id/r_pass_fill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.867" />
<Button
android:id="#+id/r_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.432"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.969" />
</android.support.constraint.ConstraintLayout>
You are calling super.onCreate(savedInstanceState); andsetContentView(R.layout.activity_main); 2 times unser on creat lifecycle , delete one of them and it should fix your problem.
I am building a client application on android, and I have a problem getting my input in EditText objects. I am having the error message : android.text.Editable android.widget.EditText.getText()' on a null object reference
package com.example.tom.friendlyhousingandroid;
import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
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.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
public EditText passwordText;
public EditText emailText;
public EditText firstnameText;
public EditText lastnameText;
public String password,email,lastname,firstname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
passwordText = findViewById(R.id.password);
emailText = findViewById(R.id.email);
firstnameText = findViewById(R.id.firstnameregister);
lastnameText = findViewById(R.id.lastnameregister);
}
public void Registration(View view){
password = passwordText.getText().toString();
email = emailText.getText().toString();
firstname = firstnameText.getText().toString();
lastname = lastnameText.getText().toString();
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://172.16.10.92:8080/school/rest/users/addUser";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("password", "fdgfr"); //Add the data you'd like to send to the server.
MyData.put("email", "fdgfr");
MyData.put("first_name", "fdgfr");
MyData.put("last_name", "fdgfr");
/*Log.d("password",password);
Log.d("firstname",firstname);
Log.d("lastname",lastname);
Log.d("email",email);*/
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
}
and the XML FILE :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".register">
<EditText
android:id="#+id/emailregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:ems="10"
android:hint="email address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lastnameregister" />
<EditText
android:id="#+id/passwordregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/emailregister" />
<EditText
android:id="#+id/lastnameregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="43dp"
android:ems="10"
android:hint="last name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstnameregister" />
<EditText
android:id="#+id/firstnameregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="first name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/launchregistration"
android:layout_width="206dp"
android:layout_height="wrap_content"
android:layout_marginBottom="95dp"
android:layout_marginTop="96dp"
android:text="Register"
android:onClick="Registration"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/passwordregister" />
</android.support.constraint.ConstraintLayout>
Obviously I am missing something here. I think the initialisation is not done well and the objects are not initialised in the onCreate() method.
Your layout says
android:id="#+id/emailregister"
but your code says:
emailText = findViewById(R.id.email);
I'm betting you want to be using R.id.emailregister instead.
Id used for email and password into java code and in XML are different. Those must be same. So rewrite your java code for finding views as
passwordText = findViewById(R.id.passwordregister);
emailText = findViewById(R.id.emailregister);