package com.russell.saw;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
public class notetaker extends Activity {
public EditText edittext;
public Button save;
public String input;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notetaker);
edittext = (EditText) findViewById(R.id.edittext);
edittext.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
save = (Button)findViewById(R.id.save);
save.setOnClickListener(btnListener);
}
private OnClickListener btnListener = new OnClickListener() {
public void onClick(View v) {
input = edittext.getText().toString();
File file = new File(Environment.getExternalStorageDirectory(), "fileOut.txt");
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
writer.write(input);
writer.newLine();
writer.flush();
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
I'm not getting any file come up when i click save with this code, anyone know where i'm going wrong .
(warning: i am VERY new to android, so please don't be mean if it's blindingly obvious :3)
Related
I wanted to make a program that would output a image fron the internet by a link to the screen, but the image either appears as a cropped strip, or does not appear at all. I will be very grateful for you help
code
package com.example.myapplication2;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
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 java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText s;
private TextView d;
private Button button1;
private URL link;
private InputStream j;
private Bitmap bitmap;
private ImageView image4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = findViewById(R.id.textView12);
s = findViewById(R.id.editText1);
button1 = findViewById(R.id.button1);
image4 = findViewById(R.id.imageView3);
}
#Override
protected void onResume() {
super.onResume();
}
public void onClickStart(View view){
new Thread(new Runnable() {
#Override
public void run() {
try {
link = new URL(s.getText().toString());
try {
j = (InputStream)link.getContent();
}
catch (IOException e){
d.setText("fail");
}
}
catch (MalformedURLException e){
d.setText("fail");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
bitmap = BitmapFactory.decodeStream(j);
image4.setImageBitmap(bitmap);
}
});
}
}).start();
}
}
enter image description here
enter image description here
It is possible in incorrect handling of the permission or file type, I would appreciate your help
I am new to android development, I think that something is wrong with the Uri built = Uri.parse("/storage/sdcard0/Download/");, but I don't know what. Any help would be appreciated.
package com.example.ecobinary;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final int CREATE_FILE = 1;
private void createFile(Uri pickerInitialUri) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, "testing.txt");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, CREATE_FILE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button execute_button = findViewById(R.id.execute_button);
execute_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri built = Uri.parse("/storage/sdcard0/Download/");
createFile(built);
}
});
}
}
I am doing a saving system with sharedPreferences, the problem is that when I run the application it seems that if the String is saved but when converting it to int later it returns null values or 0...
the edit text only receives numbers, and what I try is to obtain its value as a string and then convert it to int, since I want to use that value in another activity
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView)findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
limiterStr = inputLimiter.getText().toString().trim();
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
public void Cargar(View view){
SharedPreferences limitPrefs= getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
if(!"".equals(recovaStr)) {
limiterInt = Integer.parseInt(recovaStr);
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
}
}
public void Guardar(View view){
if(mostrarLimite!=null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
}
}
}
NEW CODE!!!!********************************
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView) findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
Button btnCargarLimTEMP = findViewById(R.id.cargarTemp);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Guardar();
}
});
btnCargarLimTEMP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cargar();
}
});
}
private void Cargar() {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
try {
limiterInt = Integer.parseInt(recovaStr);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
Toast.makeText(this, "Limite de aciertos: " + limiterInt, Toast.LENGTH_SHORT).show();
}
private void Guardar() {
if (mostrarLimite != null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
limiterStr = inputLimiter.getText().toString().trim();
Toast.makeText(this, "Limite de aciertos actualizado: " + limiterStr, Toast.LENGTH_SHORT).show();
System.out.println(limiterStr);
}
}
}
I am having trouble trying to figure out how to save user inputted data into my app. I'm attempting to create a mock basketball statistics app that will store stats per each day and then average out the different stats. Before I can do any of the actual math, though, I cannot figure out how to save the data and load it.
This is the code that I have so far for both activities:
Main Activity
package com.miahollins.basketballfinal;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
int gamesp, gamest,points,perfoul;
Button btn;
int year_x,month_x,day_x;
static final int DIALOG_ID=0;
EditText games, game2, game3, game4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText game1 = (EditText) findViewById(R.id.games);
final EditText game2 = (EditText) findViewById(R.id.games2);
final EditText game3 = (EditText) findViewById(R.id.games3);
final EditText game4 = (EditText) findViewById(R.id.games4);
Button results = (Button) findViewById(R.id.button);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
results.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gamesp = Integer.parseInt(game1.getText().toString());
gamest = Integer.parseInt(game2.getText().toString());
points = Integer.parseInt(game3.getText().toString());
perfoul = Integer.parseInt(game4.getText().toString());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key1", gamesp);
editor.putInt("key2", gamest);
editor.putInt("key3", points);
editor.putInt("key4", perfoul);
editor.commit();
startActivity(new Intent(MainActivity.this, Status.class));
}
});
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
showDialogOnButtonClick();
}
public void save(View view){
String value = games.getText().toString();
String file_name="stats";
try {
FileOutputStream fileOutputStream = openFileOutput(file_name,MODE_PRIVATE);
fileOutputStream.write(value.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(),"Message Saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showDialogOnButtonClick(){
btn=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if (id==DIALOG_ID)
return new DatePickerDialog(this,dPickerListener,year_x,month_x,day_x);
return null;
}
private DatePickerDialog.OnDateSetListener dPickerListener= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x=year;
month_x=monthOfYear+1;
day_x=dayOfMonth;
Toast.makeText(MainActivity.this,year_x+" / " + month_x+" / "+day_x,Toast.LENGTH_LONG).show();
}
};
}
Second Activity
package com.miahollins.basketballfinal;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Status extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status);
}
public void load(View view){
try {
String Stats;
FileInputStream fileInputStream = openFileInput("stats");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((Stats=bufferedReader.readLine())!=null){
stringBuffer.append(Stats + "\n");
}
TextView load = (TextView)findViewById(R.id.textView);
load.setText(stringBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Any help would be greatly appreciated!
The list loads with all the strings , and when matched , shows the matched items . But , I want that list shows only when search is typed in , and the list has only the items searched for .
package com.example.searchlistview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
private static final String TAG = "SearchViewFilterMode";
private SearchView mSearchView;
String data,temp,users;
private ListView mListView;
private ArrayAdapter<String> mAdapter;
private final ArrayList<String> mstrings_arr=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
try
{
ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://192.162.1.126:1234/www/search_reg_users.php");
HttpResponse res=client.execute(post);
InputStream inp=res.getEntity().getContent();
BufferedReader bf=new BufferedReader(new InputStreamReader(inp));
//since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code
data="";
temp="";
while((temp=bf.readLine())!=null)
{
data=data+temp;
}
JSONArray array=new JSONArray(data);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
users=object.getString("username");
mstrings_arr.add(users);
Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
mListView.setAdapter(mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
mstrings_arr));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.cheese_hunt_hint));
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
}
After the above code , I tried , setting the visibility of the listview to be VISIBILE only when a match is found . It is working for only one search instance , and if a match is found , entire list is returned .
What is I wish to get , are as follows :
Enter a search in search box
If that search matches any item in the list item
ONLY THEN , the list is displayed but with ONLY MATCHED ITEM
else {
mListView.setFilterText(newText.toString());
mListView.setVisibility(View.VISIBLE);
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
You need to use addTextChangedListener to solve your issue here. I've worked on similar thing.
addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
}
}
});
AutoCompleteTextView served the purpose , finally
package com.example.searchlistview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.Layout;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
//public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
public class MainActivity extends Activity{
private static final String TAG = "SearchViewFilterMode";
private SearchView mSearchView;
String data,temp,users;
private ListView mListView;
private final ArrayList<String> mstrings_arr=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
ArrayAdapter<String> mAdapter=new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,mstrings_arr);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
try
{
ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://192.168.1.16:1234/www/search_reg_users.php");
HttpResponse res=client.execute(post);
InputStream inp=res.getEntity().getContent();
BufferedReader bf=new BufferedReader(new InputStreamReader(inp));
//since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code
data="";
temp="";
while((temp=bf.readLine())!=null)
{
data=data+temp;
}
JSONArray array=new JSONArray(data);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
users=object.getString("username");
mstrings_arr.add(users);
Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
//AutoCompleteSearchView
AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(mAdapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
XML , for the same is :
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="36dp"
android:layout_marginTop="17dp"
android:ems="10"
android:text="">
<requestFocus />
</AutoCompleteTextView>